Mark
Mark

Reputation: 5108

encrypt and decrypt a string with node

Im testing this encryption/decryption code found here. The code is:

var crypto = require('crypto');

var encrypt = function(text){
    var algorithm = 'aes-256-ctr';
    var password = 'gh6ttr';
    var cipher = crypto.createCipher(algorithm,password)
    var crypted = cipher.update(JSON.stringify(text),'utf8','hex')
    crypted += cipher.final('hex');
    return crypted;
}

var decrypt = function(text){
    var algorithm = 'aes-256-ctr';
    var password = 'gh6ttr';
    var decipher = crypto.createDecipher(algorithm,password)
    var dec = decipher.update(JSON.stringify(text),'hex','utf8')
    dec += decipher.final('utf8');
    return dec;
}

var encrypted = encrypt('test');
console.log('encrypted is ', encrypted);

var decrypted = decrypt(encrypted);
console.log('decrypted is ', decrypted);

The results are:

encrypted is  66b1f8423a42
decrypted is  

decrypted is always blank. Any idea why this code doesn't work?

Upvotes: 0

Views: 1900

Answers (3)

Salketer
Salketer

Reputation: 15711

It's because you use JSON.stringify on an encrypted string...

var decrypt = function(text){
    var algorithm = 'aes-256-ctr';
    var password = 'gh6ttr';
    var decipher = crypto.createDecipher(algorithm,password)
    var dec = decipher.update(text,'hex','utf8')
    dec += decipher.final('utf8');
    return JSON.decode(dec);
}

EDIT: I need to note that since your question is "encrypt and decrypt a string with node" there is absolutely no reason to use the JSON functions in those two functions.

Upvotes: 2

A. A. Sebastian
A. A. Sebastian

Reputation: 538

Have look at the code below :

Encrypt the text 'abc'

var mykey = crypto.createCipher('aes-128-cbc', 'mypassword');
var mystr = mykey.update('abc', 'utf8', 'hex')
mystr += mykey.update.final('hex');

console.log(mystr); //34feb914c099df25794bf9ccb85bea72 

Decrypt back to 'abc'

var mykey = crypto.createDecipher('aes-128-cbc', 'mypassword');
var mystr = mykey.update('34feb914c099df25794bf9ccb85bea72', 'hex', 'utf8')
mystr += mykey.update.final('utf8');

console.log(mystr); //abc 

Hope that helps,

Good Luck, Cheers

Ashish Sebastian

Upvotes: 0

robertklep
robertklep

Reputation: 203514

You shouldn't JSON-stringify the encrypted text when decrypting:

var dec = decipher.update(text, 'hex', 'utf8')

Upvotes: 1

Related Questions