Search code examples
javamd5messagedigest

Get MD5 String from Message Digest


I understand how it works but if I want to print out the MD5 as String how would I do that?

public static void getMD5(String fileName) throws Exception{
    InputStream input =  new FileInputStream(fileName);
    byte[] buffer = new byte[1024];

    MessageDigest hash = MessageDigest.getInstance("MD5");
    int read;
    do {
        read = input.read(buffer);
        if (read > 0) {
            hash.update(buffer, 0, read);
        }
    } while (read != -1);
    input.close();
}

Solution

  • Try this

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