Encryption In Salesforce Apex

I recently had a use case for storing a username and password inside out Salesforce instance in such a way where I could easily access and use it from an Apex class.  Right away I knew I would need to use the Crypto library but I wasn’t sure how.  After some careful research here is what I ended up doing.

I first created a custom setting and marked it as protected.  This is going to be used to store the private key needed to decrypt the password.  I called it Soap_API_Key__c and it had one field, also called key__c.

For the next part, I opened a developer console and popped up a Anonymous Execution tab so that I could generate a key:

Now I opened the log, and looked for the debug output.  The private key was shown – and so I copied it over to the protected setting field.  Great, so we now have our private key.

Next we had to actually encrypt the sensitive data that we wanted to protect using the key we just generated:

Now when this was executed, the encrypted data was displayed in the developer debug console.  All we did after this was store the encrypted string in a custom label for later use.

So now in any Apex class where we need access to this sensitive data, we can use the following logic, grab the encrypted string from the custom label, grab the private key from the custom setting and use it to decrypt:

Hope this was useful.

Picture credit: wired.co

Leave a reply:

Your email address will not be published.

Site Footer