AES key derivation function

房东的猫 提交于 2019-12-03 14:08:33

问题


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?

来源:https://stackoverflow.com/questions/8357941/aes-key-derivation-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!