Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MD5 checksum from input stream

Tags:

java

md5

I'm trying to get the md5 sum of an input stream but the string I get is encrypted incorrectly.

The md5 string I'm getting is: ä?E´]Õaá*TàŠöJ

When it should be: e48f0b45b45dd56102e12a54e08af64a

Can you spot what I'm doing wrong? Here is a working program:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class main {

public static void main(String[] args) throws IOException {

    byte[] fileContents = new byte[15 * 10000000];

    FileOutputStream out = new FileOutputStream("C:\\testFile");
    out.write(fileContents);
    out.close();

    File file = new File("C:\\testFile");
    FileInputStream fs = new FileInputStream(file);

    System.out.println(new String(getBytesOfMd5(fs)));

}

public static byte[] getBytesOfMd5(InputStream is) throws IOException {
    byte[] buffer = new byte[1024];
    MessageDigest complete = null;
    try {
        complete = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        return null;
    }

    int numRead;
    do {
        numRead = is.read(buffer);
        if (numRead > 0) {
            complete.update(buffer, 0, numRead);
        }
    } while (numRead != -1);

    is.close();
    return complete.digest();
}
}
like image 435
visc Avatar asked Apr 26 '26 09:04

visc


2 Answers

The method digest() returns the hash as bytes. Then you tried to turn those bytes into a string directly.

What you wanted is to convert each of those bytes into two hexadecimal digits. Here is the code:

byte[] hash = complete.digest();
StringBuilder sb = new StringBuilder();
for (byte b : hash)
  sb.append(String.format("%02x", b & 0xFF));
String hexHash = sb.toString();
System.out.println(hexHash);
like image 139
Nayuki Avatar answered Apr 27 '26 23:04

Nayuki


You just need to convert the byte array into hex:

import javax.xml.DatatypeConverter;

String hex = DatatypeConverter.printHexBinary(getBytesOfMd5(fs));

NB: you can also wrap your InputStream with a DigestInputStream to have it automatically compute the digest for you as you read the stream.

like image 29
Alnitak Avatar answered Apr 27 '26 22:04

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!