Reputation: 40064
Why does this not print "hello"?
var cipher = crypto.createCipheriv('rc4', 'secret', '');
crypt = cipher.update('hello', 'binary', 'utf8');
crypt += cipher.final('utf8');
var decipher = crypto.createDecipheriv('rc4','secret', '');
data = decipher.update(crypt, 'binary', 'utf8');
data += decipher.final('utf8');
console.log(data); // prints e/l
Upvotes: 4
Views: 2048
Reputation:
Woking code:
var crypto = require('crypto');
var ecr = function(str)
{
var cipher = crypto.createCipher('aes-256-cbc', 'passphase');
var cryptedBuffers = [cipher.update(new Buffer(str))];
cryptedBuffers.push(cipher.final());
var crypted = Buffer.concat(cryptedBuffers);
return crypted;
};
var dcr = function(str)
{
var dcipher = crypto.createDecipher('aes-256-cbc', 'passphase');
var dcryptedBuffers = [dcipher.update(new Buffer(str))];
dcryptedBuffers.push(dcipher.final());
var dcrypted = Buffer.concat(dcryptedBuffers)
.toString('utf8');
return dcrypted;
};
console.log(dcr(ecr('hello test')));
Upvotes: 1
Reputation: 379
utf8 is not a valid cipher.final() option, you want binary. Try this.
var cipher = crypto.createCipheriv('rc4', 'secret', '');
crypt = cipher.update('hello', 'utf8', 'binary');
crypt += cipher.final('binary');
var decipher = crypto.createDecipheriv('rc4','secret', '');
data = decipher.update(crypt, 'binary', 'utf8');
data += decipher.final('utf8');
console.log(data);
Upvotes: 6