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!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0