Get MD5 String from Message Digest

2019-01-31 07:07发布

问题:

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

回答1:

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


回答2:

You can get it writing less:

String hex = (new HexBinaryAdapter()).marshal(md5.digest(YOUR_STRING.getBytes()))


回答3:

    String input = "168";
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] md5sum = md.digest(input.getBytes());
    String output = String.format("%032X", new BigInteger(1, md5sum));

or

DatatypeConverter.printHexBinary( MessageDigest.getInstance("MD5").digest("a".getBytes("UTF-8")))


回答4:

You can also use Apache Commons Codec library. This library includes methods public static String md5Hex(InputStream data) and public static String md5Hex(byte[] data) in the DigestUtils class. No need to invent this yourself ;)



回答5:

First you need to get the byte[] output of the MessageDigest:

byte[] bytes = hash.digest();

You can't easily print this though (with e.g. new String(bytes)) because it's going to contain binary that won't have good output representations. You can convert it to hex for display like this however:

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


回答6:

With the byte array, result from message digest:

...
byte hashgerado[] = md.digest(entrada);
...

for(byte b : hashgerado)
    System.out.printf("%02x", Byte.toUnsignedInt(b));

Result (for example):
89e8a9f68ad3c4bba9b9d3581cf5201d



回答7:

/**
 * hashes:
 * e7cfa2be5969e235138356a54bad7fc4
 * 3c9ec110aa171b57bb41fc761130822c
 *
 * compiled with java 8 - 12 Dec 2015
 */
public static String generateHash() {
    long r = new java.util.Random().nextLong();
    String input = String.valueOf(r);
    String md5 = null;

    try {
        java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        //Update input string in message digest
        digest.update(input.getBytes(), 0, input.length());
        //Converts message digest value in base 16 (hex)
        md5 = new java.math.BigInteger(1, digest.digest()).toString(16);
    }
    catch (java.security.NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return md5;
}


回答8:

FYI...

In certain situations this did not work for me

md5 = new java.math.BigInteger(1, digest.digest()).toString(16);

but this did

StringBuilder sb = new StringBuilder();

for (int i = 0; i < digest.length; i++) {
    if ((0xff & digest[i]) < 0x10) {
        sb.append("0").append(Integer.toHexString((0xFF & digest[i])));
    } else {
        sb.append(Integer.toHexString(0xFF & digest[i]));
    }
}

String result = sb.toString();


回答9:

Call hash.digest() to finish the process. It will return an array of bytes.

You can create a String from a byte[] using a String constructor, however if you want a hex string you'll have to loop through the byte array manually and work out the characters.



回答10:

Shortest way:

String toMD5(String input) {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] raw = md.digest(input.getBytes());
    return DatatypeConverter.printHexBinary(raw);
}

Just remember to handle the exception.



回答11:

This is another version of @anything answer:

StringBuilder sb = new StringBuilder();

for (int i = 0; i < digest.length; i++) {
    if ((0xff & digest[i]) < 0x10) {
        sb.append("0").append(Integer.toHexString((0xFF & digest[i])));
    } else {
        sb.append(Integer.toHexString(0xFF & digest[i]));
    }
}

String result = sb.toString();