I've posted this at SO as well where it has nicer formatting, but I'll
include the question here as well.  See
http://stackoverflow.com/questions/42147559/java-cryptocipher-doesnt-consume-all-input-bytes

I'm trying to convert from using Chilkat's proprietary decryption library
to Apache's commons codec.

I have 2 example encrypted inputs I'm working with. The first is 16 bytes
and the second is 96 bytes. The first one works great, but on the second
one the CryptoCipher doesn't appear to be consuming the last 16 bytes.

Here's some example code of the setup and decryption and the output:

   Properties properties = new Properties();
    CryptoCipher crypt =
CryptoCipherFactory.getCryptoCipher("AES/CBC/PKCS5Padding", properties);
    MessageDigest digest = MessageDigest.getInstance("SHA-256");

    byte[] hashedKeyBytes = digest.digest("SHARED_SECRET".getBytes(
            StandardCharsets.UTF_8));
    MessageDigest ivDigest = MessageDigest.getInstance("MD5");

    byte[] ivBytes =
ivDigest.digest("SHARED_SECRET".getBytes(StandardCharsets.UTF_8));
    final SecretKeySpec key = new SecretKeySpec(hashedKeyBytes, "AES");
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    crypt.init(Cipher.DECRYPT_MODE, key, iv);

    ByteBuffer encBuffer = ByteBuffer.allocateDirect(enc.length);
    System.out.println("--" + enc.length);
    encBuffer.put(enc);
    encBuffer.flip();
    System.out.println("encln " + encBuffer.limit());

    ByteBuffer decoded = ByteBuffer.allocateDirect(bufferSize);
    CryptoCipher crypt = init();

    System.out.println("consume " + crypt.update(encBuffer, decoded));
    System.out.println("finish " + crypt.doFinal(encBuffer, decoded));
    decoded.flip();
    return asString(decoded);

This produces these 2 outputs for the 2 inputs:

Short input:

--16
encln 16
consume 0
finish 13
Long input:

--96
encln 96
consume 80
finish 3

As you can see it's only consuming 80 bytes out of the input... Since the
shorter input produces the correct output as compared to what Chilkat
produced, I'm not sure where to approach this to get it to work with the
longer input.

When I print out the string representation of the decrypted contents, there
are 33 characters missing from the end that should be there.

Reply via email to