【问题标题】:Encrypting a string in PHP vs NodeJS在 PHP 与 NodeJS 中加密字符串
【发布时间】:2019-12-07 04:15:01
【问题描述】:

我正在尝试在 PHP 中加密(创建哈希)字符串并复制 NodeJS 中的行为。我不担心琴弦上的安全性。两个字符串应该匹配。

这是我拥有的 PHP 代码:

$key = 'supersecretkey';

$plaintext = "example string to encrypt";
$cipher = "rc4-hmac-md5";

$encryptedText = openssl_encrypt($plaintext, $cipher, $key);

echo $encryptedText . "\n";

这是我的输出

> php crypto.php
cRRDH1KSTZmbWLx+h0Q/l17jfDeAsQb/GA==

这是我尝试过的NodeJS:

var crypto = require('crypto'),
  algorithm = 'rc4-hmac-md5',
  password = 'supersecretkey';

function encrypt(text){
  var cipher = crypto.createCipher(algorithm,password)
  var crypted = cipher.update(text,'utf8','hex')
  crypted += cipher.final('hex');
  return crypted;
}

var hw = encrypt("example string to encrypt")
// outputs hello world
console.log(hw);

这是输出:

> node crypto.js
7ddd856a0227489b5cabda26e82eb99fb0c2ec9b6dfb477d43

为什么这些值不同,如何使它们相同?

【问题讨论】:

    标签: php node.js encryption


    【解决方案1】:

    虽然我不熟悉这两个特定的 API,但我确实注意到您在 openssl 中使用了一个初始化向量,而不是在 node.js 中。我会尝试使用 Node.js crypto.createCiperhiv 表单 (https://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv_options) 并确保对 php 和 node.js 使用相同的确切初始化向量字节(您应该能够创建一些任意的 ascii 字符串,例如“我的初始化向量”,大小合适)。

    (初始化向量是加密密码的另一个配置输入,充当引入额外随机性/可变性的种子)

    【讨论】:

    • 我从 PHP 代码中删除了初始化向量,因为它实际上对该密码算法没有任何作用。我已经编辑了 OP 并附上了结果(这是相同的字符串)。
    猜你喜欢
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    相关资源
    最近更新 更多