Encrypting and Decrypting on Salesforce and Node.js

Need to send secure messages back and forth between Salesforce and Node.js?  Whether it’s Heroku, AWS, or somewhere else, Node.js is an important platform to be able to communicate securely with Salesforce on.

Salesforce provides a fairly robust Crypto class.  I like the AES256 with Managed initialization vector (aka IV) that Salesforce provides.  The IV is 16 bytes of random/pseudorandom data that salts the encryption so the output is different every time even if the input is the same.  This prevents hackers from being able to spot patterns in the encrypted data, and makes it very difficult to brute force.  The IV gets prepended to the encrypted message so it is available on the other end when decrypting.

In Salesforce, Crypto.encryptWithManagedIV() and Crypto.decryptWithManagedIV() handle creating the IV, and prepending and parsing of the IV.

It’s pretty simple to build encryption and decryption using these methods on the Salesforce platform, see the example here.

But when it comes times to send and receive these encrypted messages on another platform, Node.js in this case, it becomes more difficult.  Managing the IV must be handled differently.  I found an article on how to do this with Java and a partial answer for Node.js.  But I couldn’t seem to find a complete, working example for Salesforce <-> Node.js.  So after I figured out how to make this work on my own, I thought I should blog about it to save others the trouble!



Here is example code of encrypt and decrypt, with some values from Node.js also included to be decrypted on Saleforce.

public class Encrypt {

    private static final Blob KEY = EncodingUtil.base64Decode('LHDK5bekAHJOFfXXzkd5uR/AoLBNPDNLIMAK8M0xss8=');    


//execute anonymous example:

String secret = 'Shhhh..  This is a secret.';
System.debug('1: ' + secret);

String encrypted = Encrypt.encryptString(secret);
System.debug('2: ' + encrypted);

String encryptedAgain = Encrypt.encryptString(secret);
System.debug('3: ' + encryptedAgain);

System.debug('4: ' + Encrypt.decryptString(encrypted));
System.debug('5: ' + Encrypt.decryptString(encryptedAgain));

String encryptedfromNodeJS = 'cLaipdqsdGM/z+e+QjpqjUKeeQR26XSJdpUvgNE1areZHhB8DeAA+9xOgZO+wEe9';
System.debug('6: ' + encryptedfromNodeJS);

String encryptedfromNodeJSagain = '1NfNnjF5ROu3W9O8G14yzpjbpLDlEYjOjg/v1or5f7OgNZj+p/v3gdj5+NCR6olD';
System.debug('7: ' + encryptedfromNodeJSagain);

System.debug('8: ' + Encrypt.decryptString(encryptedfromNodeJS));
System.debug('9: ' + Encrypt.decryptString(encryptedfromNodeJSagain));

    public static String encryptString(String clearText) {
        String encryptedText = null;
        Blob encryptedBlob = Crypto.encryptWithManagedIV('AES256', KEY, Blob.valueOf(clearText));
        encryptedText = EncodingUtil.base64Encode(encryptedBlob); 
        return encryptedText;
    public static String decryptString(String encryptedText) {
        String clearText = null;
        Blob encryptedBlob = EncodingUtil.base64Decode(encryptedText);
        Blob decryptedBlob = Crypto.decryptWithManagedIV('AES256', KEY, encryptedBlob);
        clearText = decryptedBlob.toString();
        return clearText;


We can run this code in execute anonymous and we can see that we encrypt the same value twice, get two different encrypted values which decrypt to the same value.  We also decrypt two different encrypted values which came from Node.js and they decrypt to the same value.



Here is example code of encrypt and decrypt, with some values from Salesforce also included to be decrypted on Node.js.

var KEY = Buffer.from('LHDK5bekAHJOFfXXzkd5uR/AoLBNPDNLIMAK8M0xss8=', 'base64');
const crypto = require('crypto');

var secret = 'Shhhh..  This is a secret.';
console.log('1: ' + secret);

var encrypted = encryptString(secret);
console.log('2: ' + encrypted);

var encryptedAgain = encryptString(secret);
console.log('3: ' + encryptedAgain);

console.log('4: ' + decryptString(encrypted));
console.log('5: ' + decryptString(encryptedAgain));

var encryptedfromSFDC = 'eFSWOcUjUiXKcfM+szX9HnjOZNTTCTUrxu82cwV0KR6AHNmp4X9PmNX8eQf4H1fG';
console.log('6: ' + encryptedfromSFDC);

var encryptedfromSFDCagain = 'Ed2oiBbyhZYm7P3kDvT7jYkg1p5e6Tb4xEEGaOPe/UznnZxEbr9pEmY6WVTWlWL6';
console.log('7: ' + encryptedfromSFDCagain);

console.log('8: ' + decryptString(encryptedfromSFDC));
console.log('9: ' + decryptString(encryptedfromSFDCagain));

function encryptString(clearText) {
	var encryptedText = null;

	var textBuffer = new Buffer(clearText, 'utf-8');
	var iv = crypto.randomBytes(16);

	var cipher = crypto.createCipheriv('aes-256-cbc', KEY, iv);
	var encryptedBuffer = cipher.update(textBuffer);
	encryptedText = Buffer.concat([iv, encryptedBuffer, cipher.final()]).toString('base64');

	return encryptedText;	

function decryptString(encryptedText) {
	var clearText = null;

	var encryptedBlob = new Buffer(encryptedText, 'base64');
	var iv = encryptedBlob.slice(0, 16);
	var textBuffer = encryptedBlob.toString('base64', 16);

	var decipher = crypto.createDecipheriv('aes-256-cbc', KEY, iv);
	clearText = decipher.update(textBuffer,'base64','utf-8');
	clearText += decipher.final('utf-8'); 
	return clearText;


We can run this code via command line and see that we encrypt the same value twice, get two different encrypted values which decrypt to the same value.  We also decrypt two different encrypted values which came from Salesforce and they decrypt to the same value.

Now you can talk securely back and forth between Salesforce and Node.js to your heart’s content!

Here is the full code on GitHub: https://github.com/danieljpeter/SalesforceNodeEncryption




Hack your Dreamforce experience to make it even more #Awesome

Dreamforce is the largest software event there is.  If you are a cloud computing practitioner, it is the best opportunity of the year to learn, network, and get inspired.  But it can also be overwhelming if you don’t approach it with the right mindset, or show up unprepared.

I’ve attended Dreamforce 5 times before, and put together some unique tips for you to get the best experience possible.  Some of these are a bit unconventional, so if you are into life-hacking, give them a try!

  1. I’ve always been local or driven in and stayed with friends in SF.  Despite the huge number of attendees, I’ve never had a problem finding parking in the local garages.  In fact, I find them to be rather empty!
  2. Many sessions are recorded.  Consider skipping some of these sessions if you don’t need to talk with the presenters or attendees live.  Take full advantage of the in-person opportunities and time shift some of the sessions to post-dreamforce video watching from the comfort of your couch at home.
  3. Walk around the dev zone and the exhibition halls and don’t hesitate to ask questions about anything which may interest you.  Heck, even things which don’t interest you!  In practically every case you will find the people working the booths will teach you something relevant you didn’t expect.  You would have never found this out if you didn’t talk to them.  Plus they are very friendly and motivated to talk to you.   Learn the art of asking the right questions, and not lingering any longer than is necessary – there is so much to see!
  4. Tweet your experiences with the #DF15 hashtag.  You’d be surprised how many people follow this hashtag, and it helps those who can’t attend to feel like they are part of it.
  5. If you decide to attend the keynotes, get there EARLY.  Consider an hour early for the main keynote as it always ends up in overflow.  You can watch the keynotes recorded, but it’s like watching star wars at home vs. on the big screen.  You work hard all year long, and a live keynote is a chance to recharge yourself and be inspired.
  6. Get excited about all the amazing demos, but remember they are just demos.  They may include features which aren’t generally available yet, or be the product of tons of custom work.  What you see might not be exactly what you get when you “open the box” when you get back home.  They represent what is possible, perhaps in the future.  They don’t always represent the current offering.
  7. The extra-curricular events put on by salesforce partners are a great networking opportunity, and provide free food and open bars.  Be sure to check out at least one of these, and enjoy in moderation.  They add a unique dimension to your dreamforce experience.  Keep an eye out for ones which provide products or services you are actually interested in, and conversation will flow naturally around this.
  8. Be careful with sessions in different buildings on campus.  For example Moscone West to Palace Hotel is a long, brisk walk to do if you have back to back sessions.  Some exercise if good, but you don’t want all your sessions to be spread out in this way.
  9. There are different free lunches to be had in different buildings.  If you happen to be in a campus hotel with sessions around lunch time, you may get something unique which isn’t offered in the Moscone area.
  10. Wifi and cellular networks become saturated to the point where they don’t work.  Find out how to change your phone settings to fall back from LTE to 4G->3G->Edge.  Using the older networks will often work when the newer ones fail.  Slow connection is better than no connection.  Don’t forget to switch it back, though!

In addition to this list, there is a Dreamforce Trail on Trailhead.  Trailhead is the new salesforce learning path tool which makes learning interactive and fun.  The dreamforce trail will teach you a ton of good information you need to know to have a successful dreamforce experience.  It will also let you get your feet wet with Trailhead if you haven’t used it before.  You earn a badge for completing it, which will make you want to learn more and earn more badges in other areas of salesforce.


Tips on Passing the Salesforce Certified Technical Architect Multiple-Choice Exam



It’s been on my “to-do” list for some time… and today I’m happy to say I passed the Salesforce Certified Technical Architect Multiple-Choice Exam!  Of course I still have the infamous review board presentation, but I thought I would share my experience thus far.

After working on the platform since 2009 and taking the other 6 exams, this one really wasn’t too bad for me. But just to be safe, I took the process very seriously. After all, it is $500 with a $250 retake fee!

Past Experience is Key

Here’s some of my hands-on experience, which was very relevant to the exam:

  • Past work with integrations.
  • Architecting a wide variety of creative solutions across all the clouds.
  • Years of heads-down development work.
  • Multi-tenant and large data related issues, such as query optimization.


I went through the study guide and marked anything I felt I needed to brush up on:

study guide

To review I watched the salesforce video training available through the partner community help and training on topics like Integration, Multi-Org strategies, Governance, and SSO / OAuth. Any topics I wanted to study and couldn’t find videos for I just searched in the help documentation and found exactly what I wanted.

A couple of bonus tips on items I recommend for study

  1. Make sure you know what all these words mean, and all the ways to use them!
    • inheritance
    • polymorphism
    • interface
    • abstract
    • extends
    • virtual
    • implements
  2. Understand all the relevant types of compliance standards (SAS, ISO, PCI, etc).

Taking the Exam

Don’t be shy about using the scratch paper they give you. You may have to calculate governor limits, sketch a rough ERD or flow chart, or use process of elimination by crossing things out.

I used 100 of the 120 minutes they gave me to complete the 60 questions. I just proceeded at a moderate and steady pace through the whole test without revisiting any of my answers. This strategy worked great this time, but on past exams I skipped questions I was unsure of and revisited them later. Once you have the rhythm of the test figured out, you aren’t as stressed about running out of time, and re-visiting seems unnecessary.

Study Guide is Great

There were some things in the study guide which weren’t on the exam, but if the exam questions are random, then perhaps someone else would those questions the next time.  Overall, I thought the study guide was a perfect tool for directing my study efforts.


If you have a true force.com understanding of 70% on the breadth and 60% of the depth you can probably pass this test with minimal study.  But the more you can study the better!  Cutting it close is stressful, and you never know what random questions you may get or any mistakes you might make.  Learn everything the right way over the years and it will sink in and most of the questions will feel like “freebies”!