2

我在客户端生成初始化向量,其中消息被加密,然后与向量一起发送到服务器进行解密。

客户代码:

            String key1 = "1234567812345678";
        byte[] key2 = key1.getBytes();


        SecretKeySpec secret = new SecretKeySpec(key2, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, secret);

        byte[] encrypted = cipher.doFinal(msg.getBytes(StandardCharsets.UTF_8));
        byte[] iv = cipher.getIV();

        String text = DatatypeConverter.printBase64Binary(encrypted);

        System.out.println("Encrypted info: " + text);

        bytebuf = ByteBuffer.allocate(1024);
        bytebuf.clear();

        // send iv

        bytebuf.put(iv);
        bytebuf.flip();
        while(bytebuf.hasRemaining()) {
            nBytes += client.write(bytebuf);
            System.out.println("Iv sent!");
        }

        bytebuf.clear();
        bytebuf.put(text.getBytes());

        bytebuf.flip();

        while(bytebuf.hasRemaining()) {
            nBytes += client.write(bytebuf);
        }

服务器代码

            LOGGER.info("Confirming write");

        byte[] iv = buf.array();

        LOGGER.info("Data packet found as {}", iv);


        LOGGER.info("Confirming write");
        String data = new String(buf.array());

        LOGGER.info("Data packet found as {}", data);


        IvParameterSpec ivspec = new IvParameterSpec(iv);
        String key1 = "1234567812345678";
        byte[] key2 = key1.getBytes();
        SecretKeySpec secret = new SecretKeySpec(key2, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");


        cipher.init(Cipher.DECRYPT_MODE, secret, ivspec);

        byte[] encrypted = DatatypeConverter.parseBase64Binary(data);
        byte[] decrypted = cipher.doFinal(encrypted);

        System.out.println("Decrypted Info: " + new String(decrypted, StandardCharsets.UTF_8));

我得到以下异常:

java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long

例如,如果我为缓冲区分配 1024 个字节,则将 32 个大小的 byte[] 发送到服务器,但在服务器上将生成一个 1024 个大小的 byte[]:

Data packet found as [-55, 119, 34, -19, -33, -20, -67, -77, 54, -111, 14, 94, 73, 98, 34, -7, 0, 0, 0, 0, 0, 0,..................

我是否走在正确的道路上?

4

1 回答 1

3

我不得不为初始化向量分配 16 个字节,而不是分配 1024 个字节。

ByteBuffer buf = ByteBuffer.allocate(16);

忘记阅读以下消息的套接字通道:

            buf = ByteBuffer.allocate(32);
        buf.clear();
        socket.read(buf);
于 2014-01-07T23:21:54.323 回答