AES encrypt with openssl decrypt using java
Java's SecretKeySpec
uses the password ASCII bytes directly as key bytes, while OpenSSL's -pass pass:...
method derives a key from the password using a key derivation function to transform the password into a key in a secure fashion. You can either try to do the same key derivation in Java (which you probably cannot if I interpret your question correctly), or use OpenSSL's -K
option to pass in a key (as hex bytes!) instead of a password.
You can find out how there.
To add a bit. I was struggling with the same problem. I was able to decrypt from Java an AES-128 encrypted message using the following settings.
I used openssl
to encrypt the data:
openssl enc -nosalt -aes-128-ecb -in data.txt -out crypted-aes.data -K 50645367566B59703373367639792442
As @Daniel suggested, the game changer is to use the -K
property. The Java configuration that let us to decrypt the generated file is the following:
final byte[] aesKey = "PdSgVkYp3s6v9y$B".getBytes(StandardCharsets.UTF_8);
final SecretKeySpec aesKeySpec = new SecretKeySpec(aesKey, "AES");
Path path = Paths.get("src/test/resources/crypted-aes.data");
final byte[] cryptedData = Files.readAllBytes(path);
final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, aesKeySpec);
final byte[] decryptedMsg = cipher.doFinal(cryptedData);
The magic happens when the hex key 50645367566B59703373367639792442
, its String
representation "PdSgVkYp3s6v9y$B"
, and the AES/ECB/PKCS5Padding
align together.