php - 如何使用 TripleDES 加密与 Node.js 和 PHP-mcrypt 获得相同的结果?

标签 php node.js encryption openssl mcrypt

这是在原生 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/

相关文章:

sql-server - 不支持使用 CommandBehavior=SequentialAccess 检索加密列 'xxx'

javascript - nodejs递归调用相同的api并顺序写入excel文件

php - 在PHP openssl_encrypt和golang河豚中匹配河豚加密

php - Centos 6 上安装的 yum list *php* 未显示任何 php 软件包,但 php -v 显示 php 安装版本

php - PDO 全局使用

node.js - sails 中的一个策略中的多个 Controller

node.js - 如何调试 aws lambda 函数?

c# - 加密名称

php - 为什么我的 $_SESSION 或我的 'if' 语句在分成两页时不会触发?

php - 通过 PHP 更新 MySQL 数据库的一行的频率是多少?