1

I'm struggling to decode a piece of AES-256 encrypted base64 coded data in node.js. The data was encoded in Salesforce. I tried various different aes algorithms but without luck.

I'm crypting and encoding the data in the developer console using anonymous APEX using this code.

String clearText = 'the quick brown fox jumps over the lazy dog';
Blob key = Blob.valueOf('abcabcabc1abcabcabc1abcabcabc132');
Blob cipherText = Crypto.encryptWithManagedIV('AES256', key, Blob.valueOf(clearText));
String encodedCipherText = EncodingUtil.base64Encode(cipherText); 
System.debug(encodedCipherText);

In node I'm trying to decrypt with the following lines. I got the "cryptoStr" from the debug output of the anonymous apex.

var crypto = require('crypto');
    algorithm = 'aes-256-cbc',
    password = 'abcabcabc1abcabcabc1abcabcabc132';

var cryptoStr = 'Q336OpFur65nt1NgGUebbgx5hmwpcH3iUEd4mXq8qVwXL91qpLSaFecgKpsVvQEiT0DOMwK3TpUksPnjbr3wKA==';

var decipher = crypto.createDecipher(algorithm,password);
decipher.setAutoPadding(false);
var dec = decipher.update(cryptoStr,'base64','utf-8');
dec += decipher.final('utf-8'); 

console.log('Decrypted content: ' + dec);

Any ideas are most welcome!

5

I found this great post by Chuck Mortimore about a similar problem but when crypting in Salesforce and decrypting in Java. I was able to port this to node and it worked great. I hope this will be useful for someone else too.

var crypto = require('crypto');

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

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

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

console.log('Decrypted content: ' + dec);
  • 1
    In Node v6 and above the iv needs to be calculated slightly differently. var iv = buf.slice(0, 16); That should save a few people some wasted brain cycles. :-) – TehNrd Oct 6 '17 at 18:06

protected by Community Apr 11 '17 at 13:15

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.