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

问题描述 投票:0回答:2

ColdFusion 的

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

使用

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

1.) 本·纳德尔使用

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

2.) Arlo Carreon 使用

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

虽然它们似乎都有效,但第一个解决方案可能会返回 1 到 4 个

=
,而第二个解决方案可能会返回 0、1 或 2 个
=
关于 Base64 Padding 的维基百科似乎表明有效的 Base64 值实际上应该只有 1 或 2 个
=

第一个解决方案似乎适用于所有 base64 值长度,但有时可能会返回 3 或 4

=
,这有点奇怪。对于余数为 1 的 Base64 值,第二个解决方案可能会失败。CF 抛出
The input and output encodings are not same.

coldfusion base64
2个回答
6
投票

规范强制要求填充(RFC 2045、3548/4648)。

实现必须在编码数据末尾包含适当的填充字符,除非引用本文档的规范明确指出否则。

修复缺失填充的正确方法是将

=
附加到
( len(value) % 4 ) eq 0
。这意味着正确填充的 Base64 字符串只能结束:

  • 没有
    =
  • =
  • ==

规范允许(“可以”)忽略过多的填充。

如果在字符串末尾发现超过允许数量的填充字符(例如,以“===”结尾的 Base 64 字符串),则多余的填充字符也可能会被忽略。


您能详细说明一下

The input and output encodings are not same.
的意思吗?这听起来像是无效的 Base64 编码字符串。您可能想检查
toBinary()
为输入返回的内容。它可能会告诉你
The parameter 1 of function ToBinary, which is now ... must be a base-64 encoded string
,这正是问题所在。


0
投票

最近我在看这个

//START SAFE64
// map base64 to a url save chars  https://stackoverflow.com/a/40415059
const bsCharMap = {
    '+': '-',
    '/': '_',
    '=': '', // note we can safly drop this if we dont care about preseving length
}; // this-sythem-will_gen~~ ;  00~~ 000~ or 0000 dependant on byte length

const sbCharMap = {
    "-": "="
    ,"_": "/"
}
//construct the regex so the code is defined in one place
const bsRegex = new RegExp(`[${Object.keys(bsCharMap).join()}]`, "g")
const sbRegex = new RegExp(`[${Object.keys(sbCharMap).join()}]`, "g")

function _btos(b64) {
    return  b64.replace(bsRegex, (match) => bsCharMap[match])
}
function _stob(s64) {
    let s = b64.replace(sbRegex, (match) => sbCharMap[match])
    while (s.length%4 !== 0) s += "=";
    return s
}

可能会更新 https://github.com/syonfox/skid

© www.soinside.com 2019 - 2024. All rights reserved.