[英]Node.js `crypto.final` make the encrypted result is different to PHP `mcrypt_encrypt`
// Both of key and IV are hex-string, but I hide them in Stackoverflow.
var secretKey = new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), // 48 chars
iv = new Buffer('bbbbbbbbbbbbbbbb', 'hex'); // 16 chars
var str = 'This string will be encrypted.';
var cipher = crypto.createCipheriv('des-ede3-cbc', secretKey, iv),
cryptedStr = cipher.update(str, 'utf8', 'base64') + cipher.final('base64');
$key = pack('H*', "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
$iv = pack('H*', "bbbbbbbbbbbbbbbb");
$string = 'This string will be encrypted.';
$text = mcrypt_encrypt(MCRYPT_3DES, $key, $string, MCRYPT_MODE_CBC, $iv);
$text_base64 = base64_encode($text);
In the same string, same algorithm and same encoding. 在相同的字符串中,使用相同的算法和编码。
Still there is a little part not match that is cipher.final()
. 仍然有一些不匹配的地方是
cipher.final()
。
Below is the real sample output. 以下是实际的示例输出。
// Node.js output.
UKBI17EIHKNM2EU48ygsjil5r58Eo1csByAIFp9GhUw=
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Same part
// PHP output.
UKBI17EIHKNM2EU48ygsjil5r58Eo1csAY4C0JZoyco=
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Same part
Why cipher.final()
make results different? 为什么
cipher.final()
会使结果有所不同?
How could make the same results in Node.js on condition that don't modify PHP code . 如果不修改PHP代码,如何在Node.js中获得相同的结果。
Since you can't change your PHP code, you will need to modify the node.js code. 由于您无法更改PHP代码,因此需要修改node.js代码。
The problem is that node.js' crypto module uses only PKCS#7 padding, whereas PHP uses only zero padding. 问题在于,node.js的加密模块仅使用PKCS#7填充,而PHP仅使用零填充。 You can however disable padding in node.js (
setAutoPadding(false)
) to implement your own zero padding: 但是,您可以在node.js(
setAutoPadding(false)
)中禁用填充以实现自己的零填充:
function zeroPad(buf, blocksize){
if (typeof buf === "string") {
buf = new Buffer(buf, "utf8");
}
var pad = new Buffer((blocksize - (buf.length % blocksize)) % blocksize);
pad.fill(0);
return Buffer.concat([buf, pad]);
}
And use it like this: 并像这样使用它:
var secretKey = new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), // 48 chars
iv = new Buffer('bbbbbbbbbbbbbbbb', 'hex'); // 16 chars
var str = 'This string will be encrypted.';
var cipher = crypto.createCipheriv('des-ede3-cbc', secretKey, iv);
cipher.setAutoPadding(false);
var cryptedStr = cipher.update(zeroPad(str, 8), 'utf8', 'base64') + cipher.final('base64');
console.log(cryptedStr);
Output: 输出:
UKBI17EIHKNM2EU48ygsjil5r58Eo1csAY4C0JZoyco=
Here is an implementation of a matching unpad function: 这是匹配的unpad函数的实现:
function zeroUnpad(buf, blocksize){
var lastIndex = buf.length;
while(lastIndex >= 0 && lastIndex > buf.length - blocksize - 1) {
lastIndex--;
if (buf[lastIndex] != 0) {
break;
}
}
return buf.slice(0, lastIndex + 1).toString("utf8");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.