last block incomplete with CipherInputStream/CipherOutputStream, even with padding AES/CBC/PKCS5Padding

后端 未结 6 2118
自闭症患者
自闭症患者 2020-12-28 18:06

Actually, I searched lot from internet and in stackoverflow too for this,

Initially I don\'t used padding in my encryption and decryption,

But Finally I got

6条回答
  •  独厮守ぢ
    2020-12-28 18:50

    Using CipherInputStream with padding is possible, switching to NoPadding is a workaround but not a solution.

    Padding is applied when CipherInputStream reaches the end of the stream. The important point is that you have to call the read() method of the CipherInputStream at least twice for getting all the data.

    The following example demonstrates reading a CipherInputStream with padding:

    public static void test() throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    
        SecureRandom rnd = new SecureRandom();
        byte[] keyData = new byte[16];
        byte[] iv = new byte[16];
        rnd.nextBytes(keyData);
        rnd.nextBytes(iv);
        SecretKeySpec key = new SecretKeySpec(keyData, "AES");
    
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
    
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        CipherOutputStream out = new CipherOutputStream(buffer, cipher);
    
        byte[] plain = "Test1234567890_ABCDEFG".getBytes();
        out.write(plain);
        out.flush();
        out.close();
        byte[] encrypted = buffer.toByteArray();
        System.out.println("Plaintext length: " + plain.length);
        System.out.println("Padding length  : " + (cipher.getBlockSize() - (plain.length % cipher.getBlockSize())));
        System.out.println("Cipher length   : " + encrypted.length);
    
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
        CipherInputStream in = new CipherInputStream(new ByteArrayInputStream(encrypted), cipher);
        buffer = new ByteArrayOutputStream();
        byte[] b = new byte[100];
        int read;
        while ((read = in.read(b)) >= 0) {
            buffer.write(b, 0, read);
        }
        in.close();
    
        // prints Test1234567890_ABCDEFG
        System.out.println(new String(buffer.toByteArray()));
    }
    

提交回复
热议问题