我有一个在Node中工作的加密代码示例,但是当我在browserify中尝试它时,我得到一个“未捕获的RangeError:无效的数组长度”
var crypto = require("crypto");
function encrypt(data, key, algorithm, encoding) {
algorithm = algorithm || "aes256";
encoding = encoding || "base64";
var cipher = crypto.createCipher(algorithm, key);
return cipher.update(data, "utf8", encoding) + cipher.final(encoding);
}
function decrypt(data, key, algorithm, encoding) {
algorithm = algorithm || "aes256";
encoding = encoding || "base64";
var decipher = crypto.createDecipher(algorithm, key);
return decipher.update(data, encoding, "utf8") + decipher.final("utf8");
}
var key = "this is a very secure key";
var data = "The quick brown fox jumps over the lazy dog.";
var encryptedData = encrypt(data, key);
console.log("Encrypted: ", encryptedData);
var decryptedData = null;
try {
decryptedData = decrypt(encryptedData, key);
console.log("Decrypted: ", decryptedData);
} catch (ex) {
console.log("Oops!", ex.stack);
}
if (data === decryptedData) {
console.log("It worked!");
} else {
console.log("Something went terribly wrong, my friend.");
}
节点输出:
$ node crypto.js
Encrypted: ClvTr5IWbgLHmgGQi81T6xtCR1RX4j5prSvFmtFr9+EXr5qKePKWcnu4tdFckh50
Decrypted: The quick brown fox jumps over the lazy dog.
It worked!
Browserify的输出:
Encrypted: ClvTr5IWbgLHmgGQi81T6xtCR1RX4j5prSvFmtFr9+E=F6+ainjylnJ7uLXRXJIedA==
Oops! RangeError: Invalid array length
一些有趣的观察结果:
Fr9+E
之后不同(约有43个字符),导致我认为问题出在加密而不是解密。data
选择较小的字符串,例如“testing”,则可以使用。整个代码都在RequireBin上。你可以做的任何事情都可以指出我正确的方向来解决这个问题。
如果我在调用decrypt
之前添加以下代码行(即解密Node的加密数据),它就可以工作。证明我的观点是错误在于加密器。
encryptedData = "ClvTr5IWbgLHmgGQi81T6xtCR1RX4j5prSvFmtFr9+EXr5qKePKWcnu4tdFckh50";
将算法设置为aes-256-ctr
将使我的测试通过Browserify,但我仍然担心browserify-crypto的aes256
会产生与Node不同的结果。
答案 0 :(得分:0)
已修复!
事实证明,这是Browserify对数据的base64编码的一个问题。它由Browserify的优秀人员合并为主人(见https://github.com/crypto-browserify/browserify-aes/pull/23)。