2

I have a bash script which uses openssl to encrypt data, and Java code which decrypts the result. Based on my earlier post, I'm now able to enter a password in openssl, and copy the resulting key/iv into Java. This relies on using the -nosalt option in openssl. I'd like to remove that option, and take password/salt/iv from openssl and pass it into a JDK key derivation function.

Here's the openssl script I'm using:

#!/bin/bash
openssl enc -aes-128-cbc -in test -out test.enc -p

When I run this, and enter a password, it prints out the following for example.

salt=820E005048F1DF74
key=16023FBEB58DF4EB36229286419F4589
iv=DE46F8904224A0E86E8F8F08F03BCC1A

When I try the same password/salt/iv in Java, I'm not able to decrypt test.enc. I tried Java code based on the answer by @erickson in this post. Here's the snippet.

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, 1024, 128);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));

If I print the "secret" that's generated, it's not the same as the "key" that openssl printed. Do I need to change one of the Java parameters to match how openssl is deriving its key?

daveloyall
  • 2,140
  • 21
  • 23
Ravi
  • 3,718
  • 7
  • 39
  • 57
  • 2
    OpenSSL enc uses either PKCS#5 1.5 or a non-standard key-derivation function depending on the digest (-md arg, or MD5 by default). And 1 iteration. The KDF is EVP_BytesToKey: http://openssl.org/docs/crypto/EVP_BytesToKey.html – indiv Dec 02 '11 at 15:33

0 Answers0