[英]Fix this mozilla base64 byte encoder
I am using https://developer.mozilla.org/en-US/Add-ons/Code_snippets/StringView 我正在使用https://developer.mozilla.org/zh-CN/Add-ons/Code_snippets/StringView
to do some base64 conversions. 做一些base64转换。 It occurs to me that there is a bug, but I am not sure how to fix it.
在我看来,有一个错误,但是我不确定如何修复它。
In my testing, if I do 在我的测试中,如果我这样做
var name = new StringView("ZipFile.zip").toBase64();
console.log("Original Text = " + StringView.makeFromBase64(name));
I do not get back my original text - I get "ZipFile.zi" 我没有得到我的原始文本-我得到了“ ZipFile.zi”
I think the library is calculating the padding wrong, but I am unsure how to fix it - The method bytesToBase64()
generates a string for this input that is WmlwRmlsZS56aXAA
and then has a regex lookahead that replaces the last two values to give the result WmlwRmlsZS56aX==
when the correct value should be WmlwRmlsZS56aXA=
我认为该库正在计算填充错误,但是我不确定如何解决该问题
bytesToBase64()
方法为此输入生成一个字符串,即WmlwRmlsZS56aXAA
,然后使用正则表达式WmlwRmlsZS56aXAA
替换最后两个值以提供结果WmlwRmlsZS56aX==
正确的值应为WmlwRmlsZS56aXA=
Below is encoding function - with the regex at the end: 下面是编码功能-带有正则表达式的结尾:
/* Base64 string to array encoding */
StringView.bytesToBase64 = function (aBytes) {
var sB64Enc = "";
for (var nMod3, nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
nMod3 = nIdx % 3;
nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);
if (nMod3 === 2 || aBytes.length - nIdx === 1) {
sB64Enc += String.fromCharCode(StringView.uint6ToB64(nUint24 >>> 18 & 63), StringView.uint6ToB64(nUint24 >>> 12 & 63), StringView.uint6ToB64(nUint24 >>> 6 & 63), StringView.uint6ToB64(nUint24 & 63));
nUint24 = 0;
}
}
return sB64Enc.replace(/A(?=A$|$)/g, "=");
};
I have tried to figure out how to fix the problem, but I am not sure if it is the regex, or the way that the encoding library is generating the sB64Enc value before it ever gets that far. 我试图弄清楚如何解决该问题,但是我不确定这是不是正则表达式,还是不确定编码库在达到此目的之前生成sB64Enc值的方式。
Is the problem that the line sB64Enc.replace(/A(?=A$|$)/g, "="); 问题是sB64Enc.replace(/ A(?= A $ | $)/ g,“ =”); should not be global -ie sB64Enc.replace(/A(?=A$|$)/, "=");
不应是全局的-ie sB64Enc.replace(/ A(?= A $ | $)/,“ =”);
I'm the author of the library. 我是图书馆的作者。 Thanks for reporting the bug!
感谢您报告错误!
The bug has been fixed now, and the code has been published also on GitHub . 该错误现已修复 ,代码也已发布在GitHub上 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.