如何解密在js中加密的节点js中的字符串

如何解密在js中加密的节点js中的字符串

问题描述:

我的客户端代码:

data.username = CryptoJS.AES.encrypt(user.username, "password");
data.password = CryptoJS.AES.encrypt(user.password, "password");

然后我发送'data'到服务器是express.js

Then I am sending 'data' to server which is express.js

var user = req.body;
var decipher = crypto.createDecipher('aes256', "password");
var decrypted = decipher.update(user.username, 'hex', 'utf-8');
decrypted += decipher.final('utf-8'); 

我收到此错误:

Error: DecipherInit error
at new Decipher (crypto.js:368:17)
at Object.Decipher (crypto.js:365:12)


CryptoJS' encrypt 函数与密码使用相同的 EVP_BytesToKey function node.js' createCipher ,与CryptoJS使用的重要区别随机盐,而节点不(强调我的):

CryptoJS' encrypt function with a password uses the same EVP_BytesToKey function node.js' createCipher, with the important difference that CryptoJS uses a random salt to derive whereas node does not (emphasis mine):


注意:createCipher使用OpenSSL功能EVP_BytesToKey导出密钥,其摘要算法设置为MD5,一次迭代,无盐


Note: createCipher derives keys with the OpenSSL function EVP_BytesToKey with the digest algorithm set to MD5, one iteration, and no salt.

您可以直接在节点中使用CryptoJS,因为CryptoJS没有任何依赖关系,或者您做密钥派生你自己在两端,使用 crypto.createCipheriv 。如果你做前者,你必须另外传递用户名和密码加密的盐到节点。

Either you directly use CryptoJS in node which is possible, because CryptoJS doesn't have any dependencies, or you do the key derivation yourself on both ends and use crypto.createCipheriv. If you do the former, you would have to additionally pass the salts of the username and password encryptions to node.

请注意, data.username 是包含盐和IV的CryptoJS cipherParams对象,但是当您转换这个字符串与 data.username.toString()的字符串,盐不再包含了,而是IV。这不是您将放入node.js函数的数据。发送 data.username.ciphertext

Note that data.username is the CryptoJS cipherParams object which contains the salt and the IV, but when you convert this to string with data.username.toString(), the salt is not included anymore, but the IV is. This is not the data that you would put into the node.js functions. Send data.username.ciphertext instead.