ByteSyzeBuddha
ByteSyzeBuddha

Reputation: 63

How do I create an encrypt and decrypt function in NodeJS?

I need to create an encryption and decryption function in my NodeJS application. Can anyone help and point me in the right direction?

Upvotes: 1

Views: 4243

Answers (1)

ByteSyzeBuddha
ByteSyzeBuddha

Reputation: 63

After a bit of digging, I was able to answer my own question... Sorry for the lack of clarity and detail. Will work on that for the next question.

I've included the functions to encrypt and decrypt, and the "helping" functions to generate a key and generate the initialization vector as well.

var crypto = require('crypto');

var encrypt = function encrypt(input, password) {
        var key = generateKey(password);
        var initializationVector = generateInitializationVector(password);

        var data = new Buffer(input.toString(), 'utf8').toString('binary');

        var cipher = crypto.createCipheriv('aes-256-cbc', key, initializationVector.slice(0,16));
        var encrypted = cipher.update(data, 'utf8', 'hex');
        encrypted += cipher.final('hex');   
        var encoded = new Buffer(encrypted, 'binary').toString('base64');

        return encoded;
};

var decrypt = function decrypt(input, password) {
        var key = generateKey(password);
        var initializationVector = generateInitializationVector(password);

        var input = input.replace(/\-/g, '+').replace(/_/g, '/');
        var edata = new Buffer(input, 'base64').toString('binary');

        var decipher = crypto.createDecipheriv('aes-256-cbc', key, initializationVector.slice(0,16));
        var decrypted = decipher.update(edata, 'hex', 'utf8');
        decrypted += decipher.final('utf8');
        var decoded = new Buffer(decrypted, 'binary').toString('utf8');

        return decoded;
};
var generateKey = function generateKey(password) {
    var cryptographicHash = crypto.createHash('md5');
    cryptographicHash.update(password);
    key = cryptographicHash.digest('hex');

    return key;
}
var generateInitializationVector = function generateInitializationVector(password) {
    var cryptographicHash = crypto.createHash('md5');
    cryptographicHash.update(password + key);
    initializationVector = cryptographicHash.digest('hex');

    return initializationVector;
}

var password = 'MyPassword';
var originalStr = 'hello world!';

var encryptedStr = encrypt(originalStr, password);
var decryptedStr = decrypt(encryptedStr, password);

Hats off to adviner for the inspiration of the solution.
His post can be here: here

I had originally gotten this working with this post by dave, but that didn't work for input values with a character length greater than 15. The updated code above works for inputs of any length.

Upvotes: 1

Related Questions