Gavin
Gavin

Reputation: 2365

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.

My understanding of the createDecipheriv is that it is effectively the mirror of createCipheriv and it should return the deciphered string. Is this not correct? If so how should the string be decrypted?

SOLVED:

.final() was required for both encoding and decoding the string. We've used it elsewhere without and my understanding was wrong.

Upvotes: 1

Views: 2193

Answers (1)

Wardrox
Wardrox

Reputation: 71

The update function doesn't return anything. You should use final to get the strings you're after.

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');

Upvotes: 1

Related Questions