Decryption using AES 256 with key and salt values using Java

10.4k views Asked by At

I'm trying to make decryption logic and knnow that encrypted string has been made using: Key: 8d6ea4d3e6f8c4f8641516baa5e42b85 transformation: AES/CBC/ISO10126PADDING salt: 1c4dd21d7ba43bdd iterations: 0 Encrypted string: JO0blEp+nEl5nNhgUqoZRJNecogM1XHIXUCatPOJycs=

Key and salt are given samples here..The main point is to show the format in which I have this data. encryption methods is based on the default JCE provider of the JDK (SunJCE).

Now based on this infromation I have above, I'm trying to build Decryption logic. Few doubts: 1. As the AES-265 is used, can it have 128 bits Key and 64 bit salt values? or I'm interpreting the information wrongly. 2. seeing the encrypted string, it looks like it is Base64 encoded value and we need to decode it while decrypting. Is my understanding correct? 3. Below is the decryption logic that I'm writing that is giving error: "javax.crypto.BadPaddingException: Given final block not properly padded" when I call doFinal() function. and I'm struck here from last three days:( . Can you please point out or give me the exact code that to be used here for decryption with having infromation:

    public static void main(String[] args) throws Exception
 {
        String encstring = "JO0blEp+nEl5nNhgUqoZRJNecogM1XHIXUCatPOJycs=";           
        String salt1 = "1c4dd21d7ba43bdd";
        String keyStr = "8d6ea4d3e6f8c4f8641516baa5e42b85";


        byte[] keyBytes = Hex.decodeHex(keyStr.toCharArray());

        SecretKey secret2 = new SecretKeySpec(keyBytes, "AES");

        byte[] iv = new byte[]{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
        AlgorithmParameterSpec params = new IvParameterSpec(iv);


        Cipher cipher2 = Cipher.getInstance("AES/CBC/ISO10126PADDING", "SunJCE");


        cipher2.init(Cipher.DECRYPT_MODE, secret2, params);  
        byte[] encryptedString = Base64.decodeBase64(encstring.getBytes());
        byte[] plaintext1 = cipher2.doFinal(encryptedString);

        System.out.println(new String(plaintext));   
        }
    }
1

There are 1 answers

2
Ebbe M. Pedersen On

First a few observations:

  • You say it's AES256 (that uses 256 bit keys) but your key looks like it might be 32 hex digits which gives 128 bit of key data.

  • You say you have a salt but AES don't use a salt. And you actually don't use the salt in your code.

  • You talk about 0 iterations, but iterations are not something you specify to AES, and it would not be 0.

My guess is that your key is actually a password used to generate a key. Somethig like:

   SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
   KeySpec spec = new PBEKeySpec(password, salt, iterations, keyLength);
   SecretKey theKey = factory.generateSecret(spec);

Take a look in the answer to this question: Java 256-bit AES Password-Based Encryption