I am using below util class to encrypt and decrypt the Salesforce Id.

Apex Class

public class EncryptDecryptUtil

    public static string encyptData(String decryptedString)
        Blob data = Blob.valueOf(decryptedString);
        Blob encryptedBlobData = Crypto.encryptWithManagedIV('AES128', encryptionKey , data );
        String base64EncryptedString = EncodingUtil.base64Encode(encryptedBlobData);
        return base64EncryptedString;

    public static string decryptData(String encryptedString)
        Blob data = EncodingUtil.base64Decode(encryptedString);
        Blob decryptedBlobData = Crypto.decryptWithManagedIV('AES128', encryptionKey , data);
        String decryptedString= decryptedBlobData.toString();
        return decryptedString;


Test Class:

public class HOJ_AppController_Test
    public static void prepareSharedTestData()
            //Inserting the custom setting for the encryption 

            Encryption__c privateKeyCustomSetting = new Encryption__c();         
            privateKeyCustomSetting.Name = 'App1';         
            privateKeyCustomSetting.Key__c = '1234567890123456';       
            insert privateKeyCustomSetting;

        Account acc = new Account(Name='Test Acct');
        insert acc ;
      String Encrypt =EncryptDecryptUtil.encyptData(acc.id);
      EncryptDecryptUtil.decryptData(Encrypt );


ERROR : While the encrypting the Data In test Class String Encrypt =EncryptDecryptUtil.encyptData(acc.id);

  • Which line is throwing the error? Please edit your post to include that info. – David Cheng Sep 27 '18 at 5:40
  • String Encrypt =EncryptDecryptUtil.encyptData(acc.id); line is throwing the Error ... This is happening in the test class only. When I run the code through Execute anonymous it works fine. – Donald Sep 27 '18 at 11:46
  • 1
    How does the Util class get access to variable encryptionKey ? Do you have it cached somehow and the value supplied by the testmethod (presumably in custom object Encryption__c) Does the testmethod encryption key agree with the structure of the org's value that you used in anonymous apex? – cropredy Sep 30 '18 at 3:42

I don't know why it's throwing that error there, but you're missing the closing curly bracket on the prepareSharedTestData method. Fix that and it should do the trick.

  • The close bracket should yield a compile-time syntax error, though. I think cropredy's comment is on the money - that key variable is probably null, and its initialization has been elided from the post. – David Reed Oct 1 '18 at 21:19

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.