首页 > 解决方案 > NodeJS:createCipheriv 应该提供与之前的 createCipher 相同的输出

问题描述

目前,我正在使用旧版本的 crypto.js 来加密和解密字符串。
以下是我的加密代码 -

const encrypt = (password, algorithm, encMethod) => (value) => {
  const cipher = crypto.createCipher(algorithm, password);
  return cipher.update(JSON.stringify(value), 'utf8', encMethod)
    + cipher.final(encMethod);
};

使用上面的代码我的字符串(E-mailID)
p1@yopmail.com被转换为
29c68f3bad0068c44122e734367f64557112e058c8222e3fd3908e68402ce6d5

现在createCipher不推荐使用我应该怎么做createCipheriv才能提供与上面相同的输出。

我试图通过null函数IVcreateCipheriv但我得到了错误Missing IV for cipher aes-256-cbc-hmac-sha1

标签: node.jscryptographycryptojs

解决方案


是的,最后我使用以下一些技巧解决了同样的问题 -

const bytesToKey = require('evp_bytestokey');

const encryptionToken = bytesToKey(SomePasswordString, null, 256, 16);


//Ciphering 
const cipher = crypto.createCipheriv('aes-256-cbc-hmac-sha1', encryptionToken.key, encryptionToken.iv);
return cipher.update(JSON.stringify(##VALUEtoENCRYPT##), 'utf8', 'hex') + cipher.final('hex');


//De-Ciphering 
const decipher = crypto.createDecipheriv('aes-256-cbc-hmac-sha1', encryptionToken.key, encryptionToken.iv);
return JSON.parse(decipher.update(##VALUEtoDECRYPT##, 'hex', 'utf8') + decipher.final('utf8'));

感谢您@topaco建议我使用 NPM 包evp_bytestokey


推荐阅读