visc
visc

Reputation: 4959

MD5 checksum from input stream

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();
}
}

Upvotes: 3

Views: 5440

Answers (2)

Alnitak
Alnitak

Reputation: 340055

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.

Upvotes: 2

Nayuki
Nayuki

Reputation: 18552

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);

Upvotes: 4

Related Questions