I wanted to write exact below java code in apex. I am aware of EncodingUtil.base64Decode() and Crypto class method in SF. But this byte array and Cipher, etc , am not aware of it.

 class Encyrpt{ 
 byte[] key = { 0x74, 0x68};         
try {           
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
      final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
      cipher.init(Cipher.DECRYPT_MODE, secretKey);           
      final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));  
       } catch (Exception e) { 
         System.out.println("Error while decrypting"+ e.getMessage());         

Seeking urgent help on this. Thanks In advance.

1 Answer 1


The Crypto class in Apex only supports CBC (Cipher Block Chaining) mode for AES, so based on that alone I'd say that it's not possible to port this exact code to Apex (unless you implement your own crypto, which you should absolutely not try to do).

Salesforce also produces a ciphertext with PKCS#7 padding rather than PKCS#5 (a brief search suggests that PKCS#5 is a special case of PKCS#7 with a block size of 8).

Apex doesn't provide a Byte class, but seeing as your key (which you should replace immediately since you have leaked it to the internet at large) is represented in hex, you should simply be able to port that bit to Apex by:

  • Using a List<String> instead of a byte array
  • Remove the '0x' prefix from all of the bytes
  • Use String.join() to concatenate it into a single string
  • Pass the concatenated hex string into EncodingUtil.convertFromHex(), which would give you a Blob which has a chance of being able to be passed into Crypto.decrypt()

Not the answer you're looking for? Browse other questions tagged .