Tom
Tom

Reputation: 785

Java, import file into MD5 message digest

doesn anyone know how I could use the "input" to create the MD5 hash, I don't understand where you would call it? Any helpw ould be most gratfully recieved! thanks :)

    InputStream input =  new FileInputStream(fileName);

    StringBuffer hexString = new StringBuffer();
    MessageDigest md = MessageDigest.getInstance("MD5");

    byte[] hash = md.digest();

    for (int i = 0; i < hash.length; i++) {
        if ((0xff & hash[i]) < 0x10) {
            hexString.append("0"
                    + Integer.toHexString((0xFF & hash[i])));
        } else {
            hexString.append(Integer.toHexString(0xFF & hash[i]));
        }
    }
    String string = hexString.toString();
    System.out.println(string);

Upvotes: 0

Views: 1264

Answers (2)

WhiteFang34
WhiteFang34

Reputation: 72079

This will read filename from disk and put the MD5 hash result in hex:

InputStream in = new FileInputStream(filename);
MessageDigest md = MessageDigest.getInstance("MD5");

byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) != -1) {
    md.update(buf, 0, len);
}
in.close();

byte[] bytes = md.digest();

StringBuilder sb = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
    sb.append("0123456789ABCDEF".charAt((b & 0xF0) >> 4));
    sb.append("0123456789ABCDEF".charAt((b & 0x0F)));
}
String hex = sb.toString();

Upvotes: 1

Thilo
Thilo

Reputation: 262814

You need to read from the input stream into a byte[] buffer and update the MessageDigest with it:

MessageDigest md = MessageDigest.getInstance("MD5");

byte[] buffer = new byte[8*1024];
while( int read = input.read(buffer) > 0){
   md.update(buffer, 0, read);
}
byte[] hash = md.digest();

Upvotes: 1

Related Questions