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:48

Bombe's answer is correct, however note that unless you absolutely must use MD5 (e.g. forced on you for interoperability), a better choice is SHA1 as MD5 has weaknesses for long term use.

I should add that SHA1 also has theoretical vulnerabilities, but not as severe. The current state of the art in hashing is that there are a number of candidate replacement hash functions but none have yet emerged as the standard best practice to replace SHA1. So, depending on your needs you would be well advised to make your hash algorithm configurable so it can be replaced in future.

查看更多
闭嘴吧你
3楼-- · 2018-12-31 02:49

MD5 is perfectly fine if you don't need the best security, and if you're doing something like checking file integrity then security is not a consideration. In such as case you might want to consider something simpler and faster, such as Adler32, which is also supported by the Java libraries.

查看更多
深知你不懂我心
4楼-- · 2018-12-31 02:50

Here is how I use it:

final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(string.getBytes(Charset.forName("UTF8")));
final byte[] resultByte = messageDigest.digest();
final String result = new String(Hex.encodeHex(resultByte));

where Hex is: org.apache.commons.codec.binary.Hex from the Apache Commons project.

查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 02:50

This is what I came here for- a handy scala function that returns string of MD5 hash:

def md5(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}
查看更多
冷夜・残月
6楼-- · 2018-12-31 02:51

I've found this to be the most clear and concise way to do it:

MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(StandardCharsets.UTF_8.encode(string));
return String.format("%032x", new BigInteger(1, md5.digest()));
查看更多
高级女魔头
7楼-- · 2018-12-31 02:52

Take a look at the following link, the Example gets an MD5 Hash of a supplied image: MD5 Hash of an Image

查看更多
登录 后发表回答