lodoss118
lodoss118

Reputation: 53

Nodejs decrypt AES256 help needed

Hi guys I am wondering if anyone has experience using nodejs to decrypt using aes256.

The encrypted string is base64 encoded and the first 16 bytes has the IV.

I am trying to extract the IV like below but having problems:

var crypto = require('crypto'),
    algorithm = 'aes-256-cbc',
    key = '6IAVE+56U5t7USZhb+9wCcqrTyJHqAu09j0t6fBngNo=';

function decrypt(text) {
    var buf = Buffer.from(text, 'base64');
    var iv = buf.toString('binary', 0, 16);
    //console.log(iv.length);

    //var crypt = buf.toString('base64', 16);
    var decipher = crypto.createDecipheriv(algorithm, key, iv);
    decipher.setAutoPadding(false);

    var dec = decipher.update(crypt, 'base64', 'utf-8');
    dec += decipher.final('utf-8'); 
    return dec;
}

console.log(decrypt('mIBOVqk3bDCQPupFcIWNReXrdNRnb2P+iKl35yYRgbA='));

I keep getting the "Invalid IV Length" error.

Upvotes: 2

Views: 3933

Answers (1)

Joseph
Joseph

Reputation: 5160

I believe the problem is that your key is in base64, when createDecipheriv is expecting another type.

From the docs:

The key is the raw key used by the algorithm and iv is an initialization vector. Both arguments must be 'utf8' encoded strings, Buffers, TypedArray, or DataViews. If the cipher does not need an initialization vector, iv may be null.

Also, from the encrypted data, you get the IV first from the first 16 bytes, then decrypt the rest of the data.

Here's what I believe you need, though the result is a little confused:

const crypto = require('crypto');

const decrypt = (textBase64, keyBase64, ivBase64) => {
    const algorithm = 'aes-256-cbc';
    const ivBuffer = Buffer.from(ivBase64, 'base64');
    const keyBuffer = Buffer.from(keyBase64, 'base64');

    const decipher = crypto.createDecipheriv(algorithm, keyBuffer, ivBuffer);
    decipher.setAutoPadding(false);

    let decrypted = decipher.update(textBase64, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

const encryptedMessage = 'mIBOVqk3bDCQPupFcIWNReXrdNRnb2P+iKl35yYRgbA=';
const key = '6IAVE+56U5t7USZhb+9wCcqrTyJHqAu09j0t6fBngNo=';
const iv = Buffer.from(encryptedMessage, 'base64').slice(0, 16);

// the message comes from the bytes AFTER the IV - this is what you should decrypt
const message = Buffer.from(encryptedMessage, 'base64').slice(16);

const result = decrypt(message, key, iv);
console.log(result);

Where the result is:

I AM CONFUSED╚╚╚

Upvotes: 1

Related Questions