简体   繁体   English

Node.JS加密解密不起作用

[英]Node.JS Crypto decipher not working

I have a function like: 我有一个像这样的功能:

var Crypto = require('crypto');
var string_to_encode = "some number or string";
var encrypted_string = "";
var des_key = new Buffer("key string here", "base64");
var des_iv = new Buffer(0);
var des_encryption = Crypto.createCipheriv("DES-EDE3", des_key, des_iv);
    encrypted_string = des_encryption.update(string_to_encode, "utf8", "base64");
console.log(string_to_encode+" => ["+encrypted_string+"]");

Which outputs a short encrypted string. 输出一个简短的加密字符串。

But when I try to reverse this with: 但是当我尝试用以下方法来扭转这种情况时:

var Crypto = require('crypto');
var string_to_decode = "encrypted string from above";
var deciphered_string = "empty";
var des_key = new Buffer("key string here", "base64");
var des_iv = new Buffer(0);
var des_decryption = Crypto.createDecipheriv("DES-EDE3", des_key, des_iv);
    deciphered_string = des_decryption.update(string_to_decode, "base64", "utf8");
console.log(string_to_decode+" => ["+deciphered_string+"]");

It returns an empty string (ie "encoded string from above => []") 它返回一个空字符串(即“上方的编码字符串=> []”)

I initially thought that the encoding methods might be wrong but the input will only ever be a number as a string and the result is the same for ascii and utf8. 最初,我认为编码方法可能是错误的,但是输入将只能是数字作为字符串,并且ascii和utf8的结果相同。

My understanding of the createDecipheriv is that it is effectively the mirror of createCipheriv and it should return the deciphered string. 我对createDecipheriv的理解是,它实际上是createCipheriv的镜像,它应该返回解密后的字符串。 Is this not correct? 这不正确吗? If so how should the string be decrypted? 如果是这样,应该如何解密该字符串?

SOLVED : 解决

.final() was required for both encoding and decoding the string. .final()对于编码和解码字符串都是必需的。 We've used it elsewhere without and my understanding was wrong. 我们曾经在其他地方使用过它,而我的理解是错误的。

The update function doesn't return anything. 更新函数不返回任何内容。 You should use final to get the strings you're after. 您应该使用final来获取所需的字符串。

You want to do something along the lines of: 您想按照以下方式进行操作:

des_encryption.update(string_to_encode, "utf8", "base64");
encrypted_string = des_encryption.final('base64');

and

var des_encryption.update(encryptedPassword, 'base64', 'utf8');
deciphered_string = des_encryption.final('utf8');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM