Sunday 11 October 2015

Encrypt Complete Document in Salesforce

In multiple business scenario it is required to encrypt the document which are restricted in nature, the reason is since Salesforce is a on cloud application so there could be a policy of a company to not to store documents on cloud without encrypting it.

Salesforce do provide encrypted fields to store the data securely but do not provide any standard functionality to encrypt a complete document, but I was able to encrypt the complete document successfully using custom logic.  Although I had done it two years back but now making available for everyone.

Salesforce supports multiple encryption algorithm, here I am going to use AES256 for encryption.

For encryption key, I have used Protected Custom Setting as this is a most secured place to store the data.

Please note this code can be used for any document type.

Below is the example with end to end code to encrypt a document and attach to the account. Below code can be customised using custom logic for different scenarios like in the Trigger to automatic encrypt based on the condition etc.

APEX:

// below method takes account id as parameter for which we will be inserting the attachment
Public static void encrypt(String accId, String fileName, Blob fileContent){ 
 
    //EncryptionKey__c is a custom setting where we would be storing private key, insertion is only
    //one time activity. Please be very careful in managing the KEY it should not get deleted else 
    //the document would not be decrypted.

    EncryptionKey__c ek = EncryptionKey__c.getValues('Private Key');
    if(ek.Key__c == null){
        Blob cryptoKey = Crypto.generateAesKey(256);
        ek.Key__c = EncodingUtil.base64Encode(cryptoKey);
        update(ek);
    }
    system.debug(ek.Key__c);

    Blob cryptoKey = EncodingUtil.base64Decode(ek.Key__c); 

    //calling other method which actually encrypt and upload the file as an attachment
    encryptlargeBlob(fileContent,cryptoKey, accId, fileName); 
}


// I am using Future method here because sometimes file size is big and system throws time out 
// exception, to avoid this we can use future for increased limits

@future
Public Static Void encryptlargeBlob(Blob largeBlob, Blob key, String accId, String fileName)
{
    String blobString=EncodingUtil.base64encode(largeBlob);
    
    // Below will encrypt the string and will return encrypted blob
    Blob encrypted = Crypto.encryptWithManagedIV('AES256', key, tempBlob);

    Attachment att=new Attachment();
    att.name = fileName;
    att.body = encrypted;
    att.parentId = accId;

    insert att;
}

Using above code you can easily Encrypt the document, the decryption part is different, Please find my other post for decryption.

Please be careful while playing with Encryption and do proper testing based on your scenario.
 

No comments:

Post a Comment