I am trying to implement encryption in node.js using the crypto module. Below is a snippet of my code:
var SECRET_KEY = "RANDOMKEY";
var crypto = require("crypto");
var MD5 = crypto.createHash("MD5");
MD5.update(SECRET_KEY, 'ucs2');
var hash = MD5.digest('binary');
var key = new Buffer(hash, 'binary');
var keyStart = new Buffer(8, 'binary');
key.copy(keyStart, 0, 0, 8);
var valueToEncrypt = new Buffer('password', 'utf-8').toString('binary');
var cipher = crypto.createCipheriv('des-cbc',keyStart, keyStart);
var cryptedPassword = cipher.update(valueToEncrypt, 'binary', 'base64');
cryptedPassword+= cipher.final('base64');
console.log(cryptedPassword);gives---> r4xhQ8T87z2FFkLOxkcnGg==
What I should be getting back is r4xhQ8T87z26w30I1vr9kA== I am not really sure what I am doing wrong here. Any help is really appreciated.
As it turns out, it is encrypting properly, your expected value just includes a "\r\n"
after the password, which this example code does not provide.
"r4xhQ8T87z2FFkLOxkcnGg=="
decrypts to "password"
but "r4xhQ8T87z26w30I1vr9kA=="
decrypts to "password\r\n"
.
With that out of the way, you have gone a bit crazy with encodings. It is simpler to keep everything as a Buffer
.
var SECRET_KEY = "RANDOMKEY";
var crypto = require("crypto");
var MD5 = crypto.createHash("MD5");
MD5.update(SECRET_KEY, 'ucs2');
var keyStart = MD5.digest().slice(0, 8);
var valueToEncrypt = 'password\r\n';
var cipher = crypto.createCipheriv('des-cbc', keyStart, keyStart);
var cryptedPassword = cipher.update(valueToEncrypt, 'utf8', 'base64') +
cipher.final('base64');
console.log(cryptedPassword);