这是在原生 Node.js 中使用crypto
(基于 OpenSSL)的 3DES。
var secretKey = "efd77bed61e8fdd0437df1ac";
var enchding = 'hex';
var text = 'This is test.';
var cipher = modules.crypto.createCipher('des-ede3-cbc', secretKey);
var cryptedPassword = cipher.update(text, 'utf8', enchding) + cipher.final(enchding);
output is : af4ee52e0227fe40ab2e7ddd72fb1137
但是我使用了在线 PHP-mcrypt 加密工具( link here )。
key 是efd77bed61e8fdd0437df1ac
算法为Tripledes
,模式为CBC
,并使用Hexa
输出。
output is : d4b374b7ac8df7883ab1d58c7db0b0cc
为什么这两个结果不同?
如何在 Node.js 中使用 crypto
获得相同的结果?
最佳答案
您的代码存在多个问题。
crypto.createCipher(algorithm, password)
使用密码而不是 key 。实际的 key 将从该密码派生。看来你想使用 key 而不是密码,所以你需要使用crypto.createCipheriv(algorithm, key, iv)
.PHP 的 mcrypt 模块仅应用零填充,但 Node.js 的 crypto 模块仅应用 PKCS#5/PKCS#7 填充。您应该在 PHP 中使用 PKCS#7 填充,如下所示 here 。 (示例代码中使用)
您必须在 Node.js 和 PHP 中使用相同的 IV。通常会生成一个随机 IV 并将其添加到密文之前。在解密过程中,必须将其切掉并使用。 (示例代码中未包含)
node.js
var crypto = require('crypto');
var secretKey = new Buffer("efd77bed61e8fdd0437df1ac", "utf8");
var iv = new Buffer("\0\0\0\0\0\0\0\0");
var enchding = 'hex';
var text = 'This is test.';
var cipher = crypto.createCipheriv('des-ede3-cbc', secretKey, iv);
var cryptedPassword = cipher.update(text, 'utf8', enchding) + cipher.final(enchding);
console.log(cryptedPassword);
输出:
4e91635045f42185831403057ef16749
PHP
function pkcs7pad($plaintext, $blocksize)
{
$padsize = $blocksize - (strlen($plaintext) % $blocksize);
return $plaintext . str_repeat(chr($padsize), $padsize);
}
$pt = pkcs7pad('This is test.', 8);
$iv = '\0\0\0\0\0\0\0\0';
$key = 'efd77bed61e8fdd0437df1ac';
$ct = mcrypt_encrypt(MCRYPT_3DES, $key, $pt, MCRYPT_MODE_CBC, $iv);
echo bin2hex($ct);
输出:
4e91635045f42185831403057ef16749
您似乎想对密码进行加密。密码永远不应该被加密。使用良好的哈希解决方案,例如 PBKDF2、bcrypt 或 scrypt,并通过再次哈希来验证密码。
关于php - 如何使用 TripleDES 加密与 Node.js 和 PHP-mcrypt 获得相同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30000179/