如何在javascript中解密在crypto js中加密的节点js中的字符串 [英] How to decipher string in node js which is encrypted in crypto js in javascript

查看:32
本文介绍了如何在javascript中解密在crypto js中加密的节点js中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的客户端代码:

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

然后我将数据"发送到 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 函数 node.js' createCipher,重要的区别在于 CryptoJS 使用随机盐派生而 node 没有(强调我的):

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.

要么你直接在 node 中使用 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.改为发送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.

这篇关于如何在javascript中解密在crypto js中加密的节点js中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆