如何在解码 base64 字符串之前添加填充?

How to add padding before decoding a base64 string?

ColdFusion 的 binaryDecode(input, 'base64') 很挑剔,因为填充是强制性的。

= 向 base64 值添加填充的正确方法是什么?

1.) Ben Nadel uses:

value &= repeatString( "=", ( 4 - ( len( value ) % 4 ) ) );

2.) Arlo Carreon uses

<cfset res = Len(raw_str) % 4>
<cfif res eq 2>
     <cfset raw_str &= "==">
<cfelseif res eq 3>
     <cfset raw_str &= "=">
</cfif>

虽然它们似乎都有效,但第一个解决方案可能 return 1 到 4 =,而第二个解决方案可能 return 0、1 或 2 [=13] =]的。 Wikipedia on Base64 Padding 似乎表明有效的 base64 值实际上应该只有 1 或 2 个 =

第一个解决方案似乎适用于所有 base64 值长度,但有时可能 return 3 或 4 =,这有点奇怪。对于余数为 1 的 base64 值,第二个解决方案可能会失败。CF 抛出 The input and output encodings are not same.

根据规范(RFC 2045、3548/4648),填充是强制性的。

Implementations MUST include appropriate pad characters at the end of encoded data unless the specification referring to this document explicitly states otherwise.

修复缺失填充的正确方法是追加 = 直到 ( len(value) % 4 ) eq 0。这意味着正确填充的 Base64 字符串只能以:

结尾
  • 没有=
  • =
  • ==

规范允许("may")忽略过多的填充。

If more than the allowed number of pad characters is found at the end of the string (e.g., a base 64 string terminated with "==="), the excess pad characters MAY also be ignored.


能否详细说明 The input and output encodings are not same. 是什么意思?这听起来像是无效的 Base64 编码字符串。您可能需要检查输入的 toBinary() returns。它可能会告诉你 The parameter 1 of function ToBinary, which is now ... must be a base-64 encoded string,这正是问题所在。