How can I generate an MD5 hash?

2018-12-31 01:58发布

Is there any method to generate MD5 hash of a string in Java?

30条回答
低头抚发
2楼-- · 2018-12-31 02:30

Another implementation:

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
查看更多
其实,你不懂
3楼-- · 2018-12-31 02:32

try this:

public static String getHashMD5(String string) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        BigInteger bi = new BigInteger(1, md.digest(string.getBytes()));
        return bi.toString(16);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(MD5Utils.class
                .getName()).log(Level.SEVERE, null, ex);

        return "";
    }
}
查看更多
情到深处是孤独
4楼-- · 2018-12-31 02:33

this one gives the exact md5 as you get from mysql's md5 function or php's md5 functions etc. This is the one I use (you can change according to your needs)

public static String md5( String input ) {
    try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(input.getBytes( "UTF-8" ));
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
            sb.append( String.format( "%02x", array[i]));
        }
        return sb.toString();
    } catch ( NoSuchAlgorithmException | UnsupportedEncodingException e) {
        return null;            
    }

}
查看更多
与风俱净
5楼-- · 2018-12-31 02:34

java.security.MessageDigest is your friend. Call getInstance("MD5") to get an MD5 message digest you can use.

查看更多
何处买醉
6楼-- · 2018-12-31 02:36

If you actually want the answer back as a string as opposed to a byte array, you could always do something like this:

String plaintext = "your text here";
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
  hashtext = "0"+hashtext;
}
查看更多
后来的你喜欢了谁
7楼-- · 2018-12-31 02:36

I just downloaded commons-codec.jar and got perfect php like md5. Here is manual.

Just import it to your project and use

String Url = "your_url";

System.out.println( DigestUtils.md5Hex( Url ) );

and there you have it.

查看更多
登录 后发表回答