我正在尝试在 java 中使用 AES 加密通信。
key 是硬编码的,IV 通过 SecureRandom 随机生成,并作为加密消息的前 16 个字节发送。但是,当我尝试读取收到消息的前 16 个字节时,我没有得到与生成的相同的字节数组。
这是有问题的代码:
static byte[] bytes = new byte[16];
public static byte[] encrypt(String key, String message) {
try {
SecureRandom random = new SecureRandom();
random.nextBytes(bytes);
System.out.println("Outputting generated IV:");
for(int i=0; i < bytes.length; i++){
System.out.println(bytes[i]);
}
IvParameterSpec iv = new IvParameterSpec(bytes);
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 = Base64.encodeBase64(cipher.doFinal(message.getBytes()));
System.out.println("encrypted string: "
+ Base64.encodeBase64String(encrypted));
byte[] sendMe = new byte[bytes.length + encrypted.length];
System.arraycopy(bytes, 0, sendMe, 0, bytes.length);
System.arraycopy(encrypted, 0, sendMe, 0, encrypted.length);
return sendMe;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String key, byte[] received) {
try {
byte[] initVector = Arrays.copyOfRange(received, 0, 16);
byte[] encrypted = Arrays.copyOfRange(received, 16, received.length+1);
System.out.println("Outputting received IV:");
for(int i = 0; i < initVector.length; i++){
System.out.println(initVector[i]);
}
IvParameterSpec iv = new IvParameterSpec(initVector);
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
运行一次,例如,使用文本“Hello world!”产生以下输出:
Outputting generated IV:
-79
-3
102
-103
-13
67
-63
-18
23
-114
74
26
18
-97
77
115
Outputting received IV:
36
-118
-87
-72
-119
43
101
55
50
-62
125
-98
65
35
48
-87
这显然不一样。
如有任何帮助,我们将不胜感激。
最佳答案
您正在使用加密数据覆盖您的IV:
System.arraycopy(bytes, 0, sendMe, 0, bytes.length);
System.arraycopy(encrypted, 0, sendMe, 0, encrypted.length); // Overwrites the iv
您可能想要:
System.arraycopy(bytes, 0, sendMe, 0, bytes.length);
System.arraycopy(encrypted, 0, sendMe, 16, encrypted.length);
关于java - 接收到的字节数组与发送的字节数组具有不同的值,AES 加密 + IV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35228318/