[SalesForce] Encryption / decryption with AES

I have an integration with another system which I should use the AES Algorithm.The Encryption is made in SF side – and sent in the header of an HTTP request. This made to recognize SF in internal services which won't whitelist 1M IPs. They use ECB Algorithm but I understood that SF does not support this method.

I have two methods that I can use to encrypt:

  1. with initialization vector (IV):
    Blob cryptoKey = Blob.valueOf('1234567891234567');
    String binaryString = EncodingUtil.base64Encode(cryptoKey);
    System.debug(EncodingUtil.base64Encode(cryptoKey));
    Blob data = Blob.valueOf('some Text to encrypt');
    Blob MY_IV = Blob.valueOf('0987654321098765'); 
    Blob encrypted = Crypto.encrypt('AES128', cryptoKey,MY_IV, data);
  1. with managed IV:
    Blob cryptoKey = Blob.valueOf('1234567891234567');
    Blob data = Blob.valueOf('some Text to encryped');
    Blob encrypted = Crypto.encryptWithManagedIV('AES128', cryptoKey, data);

My questions are:

  1. If I am using the second method with the managed IV, I get the plaintext with kind of gibberish at the beginning of the text when decrypted. Why it happens and how can I solve it?

  2. is there another algorithm that can serve my needs instead of AES?

  3. Is there any link or example of how can I make my own encryption?

  4. Is there any workaround to make the ECB in apex?

many thanks.

Best Answer

  1. See Decrypting ciphertext with the provided Initialization Vector (IV)

  2. You didn't describe your needs very well. You said

this made to recognize SF in internal services which won't whitelist 1M IPs

If your goal is to have the target system verify the caller, then implement oAuth JWT Bearer flow on the target side. SF supports manufacturing of JWT for this flow via Named Credential out of the box - see Named Credentials - What is the difference between JWT & JWT Token Exchange for details

3+4: The Crypto class only supports AES with CBC mode. Rolling your own encryption in Apex is pretty much a dead end. A workaround for AES/ECB is to encrypt on the client side in Javascript, you can connect that to your Apex class. Other encryption algorithms may be available in JS and they'll certainly be available if you create a service that acts as a middleware/proxy (running somewhere outside of Salesforce)

Related Topic