【问题标题】:How to use OpenSSL on node js?如何在节点 js 上使用 OpenSSL?
【发布时间】:2020-02-10 18:10:25
【问题描述】:

我正在为 node js 13.6.0 和 express 3 使用 twig js 模板。

我正在尝试将我的 php 网站转换为节点 js。在 php 中,我使用 OpenSSL 加密/解密用户信息 现在我想在节点 js 中做同样的事情。

php函数

$secure_key= "Wzm7phmY8SwjtInXk1nY";//
$cipher = "AES-128-ECB";

function encrypt($pure_string, $encryption_key) {
    global $cipher;
    $encrypted_string = openssl_encrypt($pure_string, $cipher, $encryption_key);
    return $encrypted_string;
}

function decrypt($encrypted_string, $encryption_key) {
    global $cipher;
    $decrypted_string = openssl_decrypt($encrypted_string, $cipher, $encryption_key);
    return $decrypted_string;

}

我想做完全相同的功能,但对于 node.js

如果你有任何想法请回答

【问题讨论】:

  • Node 等效项可以是 crypto.createCipher('aes-128-ecb', key)。问题是您的密钥与 128 位密钥大小不匹配,我不知道 createCipher() 如何处理更长的密钥。此外,createCipher() 已被弃用,ECB 也不是那么安全。如果我是你,我会解密所有内容,然后使用更强大的密码对其进行加密。

标签: javascript node.js encryption openssl


【解决方案1】:

你可以使用crypto npm 包。我猜这是密码盐加密/解密。所以这应该可行。

function decrypt(password, saltHex, ivAndCipherTextHex) {
  const pass = Buffer.from(password, 'ascii');
  const salt = Buffer.from(saltHex, 'hex');
  const key = crypto.pbkdf2Sync(pass, salt, 1024, 32, 'sha1');
  const cipher = Buffer.from(ivAndCipherTextHex, 'hex');
  const iv = cipher.slice(0, 16);
  const cipherText = cipher.slice(16, cipher.length);
  const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
  try {
    return Buffer.concat([
      decipher.update(cipherText),
      decipher.final(),
    ]).toString('utf8');
  } catch (err) {
    throw new Error(`Error during decrypt: ${err}`);
  }
}

这里是如何调用这个解密函数。

解密($secure_key, $salt, $cipher);

【讨论】:

  • 盐是什么??
  • 我认为encryption_key 是给你的盐。
  • 你能告诉我你用的是哪种加密/解密吗?
  • 你的意思是算法?它是 openssl openssl.org
猜你喜欢
  • 2017-03-19
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
相关资源
最近更新 更多