Calculating checksum using message digest from ByteBuffer

677 Views Asked by At

I get the data in the form of byte buffer of 32KB, and want to calculate the checksum of the whole data. So using the MessageDigest I keep updating the bytes into it and at the end I use the digest method to calculate the bytes read and calculating the checksum out of it. Checksum calculated is wrong by the above method. Below is the code. Any idea how to get it right?

private MessageDigest messageDigest;

//Keep getting bytebuffer of 32kb till eof is read
public int write(ByteBuffer src) throws IOException {
        try {
            ByteBuffer copiedByteBUffer = src.duplicate();
            try{
                messageDigest = MessageDigest.getInstance(MD5_CHECKSUM);
                while(copiedByteBUffer.hasRemaining()){
                    messageDigest.update(copiedByteBUffer.get());
                }
            }catch(Exception e){
                throw new IOException(e);
            }
            copiedByteBUffer = null;
        }catch(Exception e){
    }
}

//called after whole file is read in write function
public void calculateDigest(){
    if(messageDigest != null){
        byte[] digest = messageDigest.digest();
        checkSumMultiPartFile = toHex(digest);  // converting bytes into hexadecimal
    }
}

Updated try #2

//Will Keep getting bytebuffer of 32kb till eof is read
    public int write(ByteBuffer original) throws IOException {
            try {
                ByteBuffer copiedByteBuffer = cloneByteBuffer(original);
                messageDigest = MessageDigest.getInstance(MD5_CHECKSUM);
                messageDigest.update(copiedByteBuffer);
                copiedByteBUffer = null;
            }catch(Exception e){
        }
    }
    
    public static ByteBuffer cloneByteBuffer(ByteBuffer original) {
        final ByteBuffer clone = (original.isDirect()) ? ByteBuffer.allocateDirect(original.capacity()):ByteBuffer.allocate(original.capacity());
        final ByteBuffer readOnlyCopy = original.asReadOnlyBuffer();
        readOnlyCopy.flip();
        clone.put(readOnlyCopy);
        clone.position(original.position());
        clone.limit(original.limit());
        clone.order(original.order());
        return clone;
    }

After trying the above code i was able to see that the message digest was getting updated with all the bytes read for example: if the file size is 52,42,892 bytes then it was updated with 52,42,892 bytes. But when the checksum of file calculated using certutil -hashfile MD5 using CMD and the one calculated using the above method does not match.

0

There are 0 best solutions below