Skip to content
Advertisement

Decrypt using AES-256-ECB in Java

I have encrypted the string in PHP using AES-256-ECB.

$sString   = "test"
$sEncryptionMethod = "AES-256-ECB";
$sEncryptionKey = "mysecretkey";

openssl_encrypt($sString, $sEncryptionMethod, $sEncryptionKey)

I would like to decrypt the same using Java/Scala?

 String secret = "mysecretkey";
 SecretKeySpec skeySpec = new SecretKeySpec(encKey.getBytes("UTF-8"), "AES");
 byte[] decodedValue = Base64.getDecoder.decode(token);

 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
 int decryptMode = Cipher.DECRYPT_MODE;
 cipher.init(decryptMode, skeySpec);
 new String(cipher.doFinal(decodedValue));

I am seeing the following error? how can we decrypt the same using Java? Note: (decryption in PHP is working as expected) but I want to do this in Java

Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

Advertisement

Answer

The key has to be exactly 256 bit long. Clearly the PHP side is doing some unspecified magic voodoo to "mysecretkey" to obtain a 256 bit key. Java does not, as a rule, engage in ‘the user does not appear to know what they are doing, eh, I’ll take a wild stab in the dark’, like PHP does, which is the problem here.

Figure out how “mysecretkey” is turned into a 256-bit key, and replicate that in java.

NB: ECB is extremely insecure. It sounds like you don’t know enough about encryption to have any hope of producing an application that is actually hard to trivially break.

NB2: Note that the PHP documentation itself strongly suggests that ‘key’ should be some cryptographically derived secure source of 256 bits. The fact that openssl_encrypt actually gives you an answer when you provide a broken key is somewhat eyebrow raising. See the various comments at the PHP manual on openssl_encrypt which clearly highlight some weirdness is going on there but none are clear enough to actually explain what PHP is doing here.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement