[英]Node.js crypto module
I am trying to implement encryption in node.js using the crypto module. 我正在尝试使用crypto模块在node.js中实现加密。 Below is a snippet of my code:
以下是我的代码片段:
var SECRET_KEY = "RANDOMKEY";
var crypto = require("crypto");
var MD5 = crypto.createHash("MD5");
MD5.update(SECRET_KEY, 'ucs2');
var hash = MD5.digest('binary');
var key = new Buffer(hash, 'binary');
var keyStart = new Buffer(8, 'binary');
key.copy(keyStart, 0, 0, 8);
var valueToEncrypt = new Buffer('password', 'utf-8').toString('binary');
var cipher = crypto.createCipheriv('des-cbc',keyStart, keyStart);
var cryptedPassword = cipher.update(valueToEncrypt, 'binary', 'base64');
cryptedPassword+= cipher.final('base64');
console.log(cryptedPassword);gives---> r4xhQ8T87z2FFkLOxkcnGg==
What I should be getting back is r4xhQ8T87z26w30I1vr9kA== I am not really sure what I am doing wrong here. 我应该回去的是r4xhQ8T87z26w30I1vr9kA ==我不确定我在这里做错了什么。 Any help is really appreciated.
任何帮助都非常感谢。
As it turns out, it is encrypting properly, your expected value just includes a "\\r\\n"
after the password, which this example code does not provide. 事实证明,它正在正确加密,您的期望值仅在密码后面包含
"\\r\\n"
,而此示例代码未提供。
"r4xhQ8T87z2FFkLOxkcnGg=="
decrypts to "password"
but "r4xhQ8T87z26w30I1vr9kA=="
decrypts to "password\\r\\n"
. "r4xhQ8T87z2FFkLOxkcnGg=="
解密为"password"
但"r4xhQ8T87z26w30I1vr9kA=="
解密为"password\\r\\n"
。
With that out of the way, you have gone a bit crazy with encodings. 有了这种方式,您就对编码有些疯狂了。 It is simpler to keep everything as a
Buffer
. 将所有内容都保留为
Buffer
更为简单。
var SECRET_KEY = "RANDOMKEY";
var crypto = require("crypto");
var MD5 = crypto.createHash("MD5");
MD5.update(SECRET_KEY, 'ucs2');
var keyStart = MD5.digest().slice(0, 8);
var valueToEncrypt = 'password\r\n';
var cipher = crypto.createCipheriv('des-cbc', keyStart, keyStart);
var cryptedPassword = cipher.update(valueToEncrypt, 'utf8', 'base64') +
cipher.final('base64');
console.log(cryptedPassword);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.