+ Start a Discussion
Prem GuptaPrem Gupta 

Decrypting the base64Encoded data which is encrpyted by Java (AES256)

First of all thanks for the time to see my question.
I have a encrypted data that comes from Java webservice(AES256-base64Encoded) :

Now I also have a 32 bit key to decode it (base64Encoded):


So after decryption, I should get the following data below:


I know if I encrypt in Apex then I can use decrypt(String, Blob, Blob, Blob) or decryptWithManagedIV(String, Blob, Blob).
But in this case, I don't why I am getting error, I tried all options available . PLease find sample code:

Blob key = EncodingUtil.base64Decode('v3erqY/EGg1NI0yFHYLsMt7IuqJksxNjo1dlhsOo6Zs=');
String encodedData ='C5j45mSEdqfz4f4GnrwR2T25tizY5gb3JoVNtWp8DiYOW5d+qvPx/ODmQIQqNXpZ1YkIjLwu5BAjDh3QmlrC4DKwTvbSrVqxh7OJdGDQy60ebp0o1cmLBCJuqzAOh2KAZC6L9v4wkwEb9dFOPesImY15DySPeyYiuLHL7n2dHmyVUMcDUrp9TAm85daCyG5mKhaAy2SP8iNBPoUBWSIDDEM7vG5Ganxu6JVzG4V6zGYQlLXAi33Ct9Fs99YE02KKR4kiw52eE1nS4hwReMZnP4vuU1FxM0BZfWAdUV8m9pQ=';
Blob exampleIv = Blob.valueOf('Example of IV123');
Blob decryptedData = Crypto.decrypt('AES256', key ,exampleIv, EncodingUtil.base64Decode(encodedData));
//Blob decryptedData = Crypto.decryptWithManagedIV('AES256', key, EncodingUtil.base64Decode(encodedData));
 system.debug(decryptedData );  
below is the java encrypted code, that can be refer:

public class EncryptionTest {

       public static final String CHAR_SET = "UTF8";
       public static void main(String[] args) {
              // TODO Auto-generated method stub
              //System.out.println("Hello World");
              String key = "v3erqY/EGg1NI0yFHYLsMt7IuqJksxNjo1dlhsOo6Zs=";
              // Try the below as well
              byte [] mKeyBytes = Base64.decodeBase64(key);
              //byte [] mKeyBytes = decodeToByteArray(key.getBytes());
              javax.crypto.Cipher mDecryptCipher = null;
              javax.crypto.Cipher mEncryptCipher = null;
              //byte[] mKeyBytes;
              try {
                     // Create the SecretKeySpec using the key in mKeyBytes
                     final SecretKeySpec skeySpec = new SecretKeySpec(mKeyBytes, getAlgorithmName());
                     // Create a new Cipher instance to do decryption using ALGORITHM
                     final javax.crypto.Cipher decryptCipher = javax.crypto.Cipher.getInstance(getAlgorithmName());
                     // Initialize this Cipher as a decryption cipher and pass in the key
                     // spec to use
                     decryptCipher.init(javax.crypto.Cipher.DECRYPT_MODE, skeySpec);
                     // If the previous two steps succeeded, set this new decryption
                     // Cipher to be this class's member decryption Cipher
                     mDecryptCipher = decryptCipher;
                     // Create a new Cipher instance to do encryption using ALGORITHM
                     final javax.crypto.Cipher encryptCipher = javax.crypto.Cipher.getInstance(getAlgorithmName());
                     // Initialize this Cipher as an encryption cipher and pass in the
                     // key spec to us
                     encryptCipher.init(javax.crypto.Cipher.ENCRYPT_MODE, skeySpec);
                     // If the previous two steps succeeded, set this new encryption
                     // Cipher to be this class's member encryption Cipher
                     mEncryptCipher = encryptCipher;
              } catch (InvalidKeyException e) {
              } catch (NoSuchAlgorithmException e) {
              } catch (NoSuchPaddingException e) {
              String pStringToDecrypt = "C5j45mSEdqfz4f4GnrwR2T25tizY5gb3JoVNtWp8DiYOW5d+qvPx/ODmQIQqNXpZ1YkIjLwu5BAjDh3QmlrC4DKwTvbSrVqxh7OJdGDQy60ebp0o1cmLBCJuqzAOh2KAZC6L9v4wkwEb9dFOPesImY15DySPeyYiuLHL7n2dHmyVUMcDUrp9TAm85daCyG5mKhaAy2SP8iNBPoUBWSIDDEM7vG5Ganxu6JVzG4V6zGYQlLXAi33Ct9Fs99YE02KKR4kiw52eE1nS4hwReMZnP4vuU1FxM0BZfWAdUV8m9pQ=";
              String decryptedString;
              final byte[] encryptedBytes;
              final byte[] decryptedBytes;
        try {
              encryptedBytes = Base64.decodeBase64(pStringToDecrypt.getBytes(CHAR_SET));
              decryptedBytes = decrypt(mDecryptCipher, encryptedBytes);
            decryptedString = new String(decryptedBytes, CHAR_SET);
        } catch (UnsupportedEncodingException e) {
        } catch (Exception e) {
       protected static final byte[] decrypt(javax.crypto.Cipher decryptCipher, byte[] pBytesToDecrypt) throws Exception {
              try {
                     return decryptCipher.doFinal(pBytesToDecrypt);
              } catch (IllegalBlockSizeException ibse) {
                     throw new Exception("Failed to decrypt: ", ibse);
              } catch (BadPaddingException bpe) {
                     throw new Exception("Failed to decrypt: ", bpe);

       public static String getAlgorithmName() {
              return "AES";


The problem is that the encrypted code is not getting decrypted in apex using standard way . Please help me out.
I didn't followed your code much but here is what will surely help you on both encrypt and decrypt. You can easily change algorithm whichever you want!
public static String Encrypt(String dataToEncrypt) {
	dataToEncrypt = dataToEncrypt.trim();
	Blob key = getKey();
	Blob data = Blob.valueOf(dataToEncrypt);
	Blob encryptedData = Crypto.encryptWithManagedIV('AES128', key, data);        
	String encryptedDataBase64 =  EncodingUtil.base64Encode(encryptedData);
	System.debug(LoggingLevel.INFO, '== Encrypted Data ==' + encryptedDataBase64);
	return encryptedDataBase64;                

public static String Decrypt(String encryptedData) {
	encryptedData = encryptedData.trim();
	Blob key = getKey();        
	Blob decryptedDataBase64 = EncodingUtil.base64Decode(encryptedData);
	Blob decryptedData = Crypto.decryptWithManagedIV('AES128', key, decryptedDataBase64);
	String originalData = decryptedData.toString();
	System.debug(LoggingLevel.INFO, '== Decrypted Data ==' + originalData);
	return originalData ;

private static Blob getKey() {
	Blob key = EncodingUtil.base64Decode(orgSettings.EncryptionKey__c);
	return key;
PS: if this answers your question then hit Like and mark it as solution!
Prem GuptaPrem Gupta
Hi Sumit,
Thanks for the suggestion. But it is not working for my inputs.
I have this totally working in one of my projects. You need to carefully look at KEYS I am using, Algorithm I am using and then encoding/decoding finally. there might be something small you missing! You can try this code in apex developer console; it works for encrypt/decrypt so try to get it on same lines as that of your Java code.
Prem GuptaPrem Gupta
Sumit, The java implementation is working. I have a encrypted data and a key. It use AES256 encryption, which is created in Java. Now I am getting these details and my work is to decode in apex . The code you given will work if I encrypt in apex and then decrypt too in apex. However, i am geting encrypted code from java (Code is in my above post). Also , I am getting the key directly in response json(I am not generating it). Also, the encrypted  data and key are proper (please refer Java implementation above).
Look in this to get idea on code: https://gist.github.com/bricef/2436364

This is opposite of what you want to do but you will atleast get idea on how it works in both environments for encode and decode.
Prem GuptaPrem Gupta
Hi Sumit,
              I appreciate your effort, however we don't have MCRYPT function (or any default c variables) in apex. The situation is lots different here.
Hi Prem, 

I am facing similar issue. can you please help me with solution?

Thanks & Regards,