我试图在java中使用AES加密通信。
密钥是硬编码的,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;
}
运行一次,例如,用文本&#34; Hello world!&#34;产生了以下输出:
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
这显然不一样。
任何帮助都将不胜感激。
答案 0 :(得分:2)
您使用加密数据覆盖 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);