0

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.