AES使用openssl命令行工具加密,并在Java中解密

我有一个使用openssl工具加密的bash脚本。

#!/bin/bash key128="1234567890123456" iv="1234567890123456" openssl enc -aes-128-cbc -in test -out test.enc -K $key128 -iv $iv 

以及尝试解密脚本生成的文件的Java代码。

 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代码时,它不会打印任何内容。 脚本和Java代码之间是否存在不匹配?

第二个问题是我是否可以将其重写为使用密码而不是密钥/ iv。 为了做到这一点,有没有办法知道openssl用于给定密码的iv?

正如上面提到的@Polynomial,bash脚本和Java代码之间的键和iv不匹配。 将bash脚本更改为以下内容可以解决问题。

 #!/bin/bash key128="01020304050607080900010203040506" iv="01020304050607080900010203040506" openssl enc -aes-128-cbc -in test -out test.enc -K $key128 -iv $iv 

如果以下列方式执行openssl,它将使用密码,并打印密钥并使用iv。 该密钥和iv可以在上面的Java程序中替换。

 openssl enc -nosalt -aes-128-cbc -in test -out test.enc -p