[英]AES-128-CBC is different in Java and Linux
我想在JAVA和Linux中进行aes-128-cbc加密,但是它不断给我带来不同的结果。 例如,我想解码字符串“ my.txt”。 在Linux中,我是这样进行的:
echo -n my.txt | openssl aes-128-cbc -K 6f838655d1bd6312b224d3d1c8de4fe1 -iv 9027ce06e06dbc8b -a
我也将其编码为base64,这给了我以下结果: 86M5fwdUpQ3tbFrz0ddHJw ==
在Java中,我使用以下方法:
public static String encrypt(String key, String initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: "
+ Base64.encodeToString(encrypted, Base64.DEFAULT));
return Base64.encodeToString(encrypted, Base64.DEFAULT);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
并以相同的数据给我完全不同的结果: vgk6yxCrQ5iLFvHxMtQO7w ==
我还尝试使用具有32个符号长度iv的aes-256-cbc。 在Linux中,我使用aes-256-cbc,在Android中,我使用Spongy Castle库来实现此目的,但是它也给出了不同的结果。
我做错了什么? 或者,也许您有建议选择不同的跨平台算法进行加密。
-K
和-iv
参数需要十六进制编码的字符串。 您的密钥长度为32个字符,因此为16个字节或128位。 您的IV长度为16个字符,因此为8个字节或64位。 AES / CBC的IV必须正好为128位长。 如果不是,则必须以某种方式填充它。 您的IV最有可能用0x00字节填充以达到128位。 您将必须在Java中执行相同的操作。
另一个问题是您将十六进制编码的密钥和IV视为文本,这意味着在Java中将其视为256位密钥和128位IV。 这可能不是您想要的。 使用前,您必须从十六进制解码字符串。
让我们使用byte[] fromHex(String hexStr)
的byte[] fromHex(String hexStr)
的假想实现:
byte[] ivBytes = new byte[16];
byte[] ivBytesShort = fromHex(initVector);
System.arraycopy(ivBytesShort, 0, ivBytes, 0, ivBytesShort.length);
IvParameterSpec iv = new IvParameterSpec(ivBytes);
SecretKeySpec skeySpec = new SecretKeySpec(fromHex(key), "AES");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.