Get MD5 String from Message Digest

前端 未结 11 993
伪装坚强ぢ
伪装坚强ぢ 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
    /**
     * 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;
    }
    
    0 讨论(0)
  • 2020-12-23 21:10

    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

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

    You can get it writing less:

    String hex = (new HexBinaryAdapter()).marshal(md5.digest(YOUR_STRING.getBytes()))
    
    0 讨论(0)
  • 2020-12-23 21:21

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

    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.

    0 讨论(0)
提交回复
热议问题