AES加密与OpenSSL的命令行工具,并在Java中解密 [英] AES encrypt with openssl command line tool, and decrypt in Java
问题描述
我有使用OpenSSL工具加密一个bash脚本。
I have a bash script that uses the openssl tool to encrypt.
#!/bin/bash
key128="1234567890123456"
iv="1234567890123456"
openssl enc -aes-128-cbc -in test -out test.enc -K $key128 -iv $iv
和试图解密由脚本生成的文件的Java code。
And Java code that tries to decrypt the file produced by the script.
public class crypto {
public static void main( String[] args )
{
try {
File f = new File("test.enc");
Cipher c;
Key k;
String secretString = "01020304050607080900010203040506";
String ivString = "01020304050607080900010203040506";
byte[] secret = hexStringToByteArray(secretString);
byte[] iv = hexStringToByteArray(ivString);
c = Cipher.getInstance("AES/CBC/PKCS5Padding");
k = new SecretKeySpec(secret, "AES");
c.init(Cipher.DECRYPT_MODE, k, new IvParameterSpec(iv));
CipherInputStream cis = new CipherInputStream(new FileInputStream(f), c);
BufferedReader br = new BufferedReader(new InputStreamReader(cis));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (NoSuchAlgorithmException e) {
System.out.println(e.getMessage());
} catch (NoSuchPaddingException e) {
System.out.println(e.getMessage());
} catch (InvalidKeyException e) {
System.out.println(e.getMessage());
} catch (InvalidAlgorithmParameterException e) {
System.out.println(e.getMessage());
}
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
}
33,1 71%
当我运行Java code,它不会显示任何信息。有没有脚本和Java code之间的不匹配?
When I run the Java code, it doesn't print anything. Is there a mismatch between the script and Java code?
一个次要的问题是我是否能改写这个使用密码,而不是键/ IV。为了做到这一点,是有办法知道的OpenSSL使用一个给定的密码?静脉注射
A secondary question is whether I can rewrite this to use password instead of key/iv. In order to do that, is there a way to know the iv that openssl uses for a given password?
推荐答案
由于@Polynomial如上所述,密钥和IV的不要在bash脚本和Java code之间的匹配。改变bash脚本为以下解决问题。
As @Polynomial mentioned above, the keys and iv's don't match between the bash script and Java code. Changing the bash script to the following solves the problem.
#!/bin/bash
key128="01020304050607080900010203040506"
iv="01020304050607080900010203040506"
openssl enc -aes-128-cbc -in test -out test.enc -K $key128 -iv $iv
如果OpenSSL是以下列方式执行时,它会使用密码,并打印键和四使用。该密钥以及iv可以在上面的Java程序被取代
If openssl is executed in the following way, it will use a password, and print the key and iv used. That key and iv can be substituted in the Java program above.
openssl enc -nosalt -aes-128-cbc -in test -out test.enc -p
这篇关于AES加密与OpenSSL的命令行工具,并在Java中解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!