Get MD5 String from Message Digest

前端 未结 11 943
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 20:46

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{
            


        
相关标签:
11条回答
  • 2020-12-23 20:56

    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();
    
    0 讨论(0)
  • 2020-12-23 20:57
        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")))
    
    0 讨论(0)
  • 2020-12-23 20:57

    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.

    0 讨论(0)
  • 2020-12-23 21:05

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

    0 讨论(0)
  • 2020-12-23 21:05

    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();
    
    0 讨论(0)
  • 2020-12-23 21:07

    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();
    
    0 讨论(0)
提交回复
热议问题