接收到的字节数组的值与发送的不同,AES 加密 + IV

Received byte array has different values than sent, AES encryption + IV

我正在尝试使用 AES 在 java 中加密通信。

密钥是硬编码的,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);