1

Hi guys I am wondering if anyone has experience using nodejs to decrypt fields from Salesforce using the encryptWithManagedIV.

I have tried implementing something from this post

How to decrypt AES-256 in node.js

But keep getting the invalid IV length:

for example this is what i did:

var crypto = require('crypto');

password = '6IAVE+56U5t7USZhb+9wCcqrTyJHqAu09j0t6fBngNo=';
var cryptoStr = 'lpGtzfMaWao1hYR9SkWFHvRnHMsDCsvAy6agp9gF8huK26qeOM/sr+0nVevlkREkmhfLts6TiwE6ZZ7fMLtzbw==';

var buf = new Buffer(cryptoStr, 'base64');
var iv = buf.slice(0, 16);

var crypt = buf.toString('base64');

var decipher = crypto.createDecipheriv('aes-256-cbc', new Buffer(password, 'base64'), iv);
decipher.setAutoPadding(false);
var dec = decipher.update(crypt, 'base64', 'utf-8');
dec += decipher.final('utf-8'); 
console.log('Decrypted content: ' + dec);
1

1 Answer 1

0

The default string encoding used by the crypto module changed in v6.0.0 from binary to utf8. The answer in How to decrypt AES-256 in node.js does not work in node versions 6.0.0 or higher due to this but only requires slight modification.

If you are running node version 6 or greater, your binary iv string is being interpreted as utf8 and is most likely becoming larger than 16 bytes during the createDecipheriv conversion process due to invalid utf8 character bytes being added.

To resolve this, you can simply create a base64 buffer of your encrypted string and then slice 16 bytes from this buffer to use as your iv.

var crypto = require('crypto');

var password = 'abcabcabc1abcabcabc1abcabcabc132';
var cryptoStr = 'Q336OpFur65nt1NgGUebbgx5hmwpcH3iUEd4mXq8qVwXL91qpLSaFecgKpsVvQEiT0DOMwK3TpUksPnjbr3wKA==';

var buf = new Buffer(cryptoStr, 'base64');
var iv = buf.slice(0, 16);
var crypt = buf.toString('base64', 16);

var decipher = crypto.createDecipheriv('aes-256-cbc', password, iv);
var dec = decipher.update(crypt,'base64','utf-8');
dec += decipher.final('utf-8'); 

console.log('Decrypted content: ' + dec);
2
  • Ok I for some reason I am getting weird characters from decrypted string �V�i�B�R�Rܺw �I AM CONFUSED AAAAAAAAAAAAAAAAAAAAAAA
    – lodoss118
    Apr 16, 2017 at 0:29
  • 1
    Are you still using decipher.setAutoPadding(false); ? If so, remove this line and try again. May 5, 2017 at 2:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .