我正在用 perl 加密一个文件,并想用 java 解密。这是我的加密代码:
== Perl 中的加密 ==
$key = "1234567890123456";
$plain_text = "this is foo";
open ($fh, ">" . $output_file_path) || die ("open ($output_file_path):$!");
my $cipher = Crypt::CBC->new( -key => $key, -cipher => "Crypt::OpenSSL::AES");
$cipher->start("");
print $fh $cipher->crypt($plain_text);
这是我正在使用的解密代码,但它不起作用。
== Java 中的解密 ==
String key = "1234567890123456";
byte[] encrypted_bytes = READ_DATA_FROM_FILE
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(key.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
String plain_text = new String(cipher.doFinal(encrypted_bytes));
有人可以帮我吗?
最佳答案
您似乎没有为 perl 加密指定 IV,并且没有将 'encrypt'
传递给 perl start()
方法。这些是我注意到的直接问题。
这可能不是当前的问题,但在处理“非平凡”文本时会出现问题:您在 java 中对 byte <-> char 转换不小心(String.getBytes( )
和 new String()
)。您正在使用 java 中的方法,这些方法使用默认的平台字符编码,这可能不是您想要的。最好使用显式字符集。
关于java - 带有 AES 的 CBC : Encrypting in Perl and Decrypting in Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18175492/