Java 如何生成 MD5 哈希?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/415953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I generate an MD5 hash?
提问by Akshay
Is there any method to generate MD5 hash of a string in Java?
有没有什么方法可以在 Java 中生成字符串的 MD5 哈希?
采纳答案by Bombe
You need java.security.MessageDigest
.
你需要java.security.MessageDigest
.
Call MessageDigest.getInstance("MD5")
to get a MD5 instance of MessageDigest
you can use.
调用MessageDigest.getInstance("MD5")
以获取MessageDigest
您可以使用的 MD5 实例。
The compute the hash by doing one of:
通过执行以下操作之一来计算哈希:
- Feed the entire input as a
byte[]
and calculate the hash in one operation withmd.digest(bytes)
. - Feed the
MessageDigest
onebyte[]
chunk at a time by callingmd.update(bytes)
. When you're done adding input bytes, calculate the hash withmd.digest()
.
- 将整个输入作为 a 提供,
byte[]
并在一个操作中使用 计算散列md.digest(bytes)
。 - 通过调用一次喂
MessageDigest
一个byte[]
块md.update(bytes)
。添加完输入字节后,使用md.digest()
.
The byte[]
returned by md.digest()
is the MD5 hash.
在byte[]
返回的md.digest()
是MD5哈希值。
回答by koregan
The MessageDigest
class can provide you with an instance of the MD5 digest.
该MessageDigest
班可为您提供的MD5摘要的一个实例。
When working with strings and the crypto classes be sure to alwaysspecify the encoding you want the byte representation in. If you just use string.getBytes()
it will use the platform default. (Not all platforms use the same defaults)
使用字符串和加密类时,请确保始终指定您想要的字节表示的编码。如果您只使用string.getBytes()
它,将使用平台默认值。(并非所有平台都使用相同的默认值)
import java.security.*;
..
byte[] bytesOfMessage = yourString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
If you have a lot of data take a look at the .update(byte[])
method which can be called repeatedly. Then call .digest()
to obtain the resulting hash.
如果您有大量数据,请查看.update(byte[])
可以重复调用的方法。然后调用.digest()
以获取结果散列。
回答by frankodwyer
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.
Bombe 的回答是正确的,但是请注意,除非您绝对必须使用 MD5(例如强制使用以实现互操作性),否则更好的选择是 SHA1,因为 MD5 有长期使用的弱点。
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.
我应该补充一点,SHA1 也有理论上的漏洞,但没有那么严重。散列技术的当前状态是有许多候选替代散列函数,但还没有出现作为替代 SHA1 的标准最佳实践。因此,根据您的需要,建议您使哈希算法可配置,以便将来可以替换它。
回答by lutzh
You might also want to look at the DigestUtilsclass of the apache commons codecproject, which provides very convenient methods to create MD5 or SHA digests.
您可能还想查看apache commons codec项目的DigestUtils类,它提供了非常方便的方法来创建 MD5 或 SHA 摘要。
回答by lutzh
Take a look at the following link, the Example gets an MD5 Hash of a supplied image: MD5 Hash of an Image
回答by user49913
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;
}
回答by user49913
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.
如果您不需要最好的安全性,那么 MD5 完全没问题,如果您正在做诸如检查文件完整性之类的事情,那么安全性不是考虑因素。在这种情况下,您可能需要考虑更简单、更快速的方法,例如 Java 库也支持的 Adler32。
回答by adranale
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.
其中 Hex 是:org.apache.commons.codec.binary.Hex
来自Apache Commons 项目。
回答by Lukasz R.
Another implementation: Fast MD5 Implementation in Java
另一个实现:Java 中的快速 MD5 实现
String hash = MD5.asHex(MD5.getHash(new File(filename)));
回答by dac2009
Found this:
发现这个:
public String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
}
return null;
}
on the site below, I take no credit for it, but its a solution that works! For me lots of other code didnt work properly, I ended up missing 0s in the hash. This one seems to be the same as PHP has. source: http://m2tec.be/blog/2010/02/03/java-md5-hex-0093
在下面的网站上,我不相信它,但它是一个有效的解决方案!对我来说,许多其他代码无法正常工作,我最终在哈希中丢失了 0。这个好像和 PHP 一样。来源:http: //m2tec.be/blog/2010/02/03/java-md5-hex-0093