Get MD5 String from Message Digest

前端 未结 11 1246
伪装坚强ぢ
伪装坚强ぢ 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 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();
    

提交回复
热议问题