2

The Salesforce crypto class documentation specifies that a private key should be stored as a protected custom setting.

Please help me on this part, how can i generate a encryption key and store it in protected custom setting?.

we would like to encrypt the data and send it to external systems using SOAP web services, does anyone has any idea?

Thanks

3

First of all you need to make a protected hierarchy custom setting (MyCustomSetting__c) with field that have a crypto key in it(CRYPTO__c).

Next you need to generate your crypto key in Apex.

MyCustomSetting__c setting = MyCustomSetting__c.getOrgDefaults(); Blob cryptoKey = Crypto.generateAesKey(128); setting.CRYPTO__c = EncodingUtil.base64Encode(cryptoKey);

Next you may to use your crypto key in your code just with two simple functions. First, you can encrypt your data:

public static String encrypt(String toEncrypt){
MyCustomSetting__c setting = MyCustomSetting__c.getOrgDefaults();
Blob cryptoKey = EncodingUtil.base64Decode(setting.CRYPTO__c);

Blob data = Blob.valueOf(toEncrypt);
Blob encryptedData = Crypto.encryptWithManagedIV('AES128', cryptoKey, data);
String encryptedDataStr = EncodingUtil.base64Encode(encryptedData);

return encryptedDataStr;}

And you can to decrypt it:

public static String decrypt(String toDecrypt){
Blob encryptedData = EncodingUtil.base64Decode(toDecrypt);
MyCustomSetting__c setting = MyCustomSetting__c.getOrgDefaults();
Blob cryptoKey = EncodingUtil.base64Decode(setting.CRYPTO__c);

Blob decryptedData = Crypto.decryptWithManagedIV('AES128', cryptoKey, encryptedData);

return decryptedData.toString();}
  • Thanks for the reply! but i would like to know where should i generate the crypto key and store it in the custom setting?,i mean i need to generate the cryptokey in the same class where i am encrypting the data if i do this system will generate new key every time. i hope crypto key value shoud remain constant. please clarify. – narendhar reddy Oct 22 '15 at 14:06
  • If you want generate your crypto key just one time you can execute first snippet of code which I wrote in answer in the Execute anonymuos code in youe Developer console. Next you will use that key with two methods encrypt(data); and decrypt(data); Please check my post as answer if this helps you. – Yaroslav Maksymenko Oct 23 '15 at 7:16
  • 1
    and CRYPTO__c is not really secure as custom settings aren't encrypted. Is there a way around that? – cropredy May 15 '17 at 22:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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