How can I generate an MD5 hash?

有什么方法可以在Java中生成一个字符串的MD5哈希?


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


The MessageDigest class can provide you with an instance of the MD5 digest.

When working with strings and the crypto classes be sure to always specify 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)

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.


如果你真的想把答案作为字符串而不是字节数组,你总是可以这样做:

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;
}
链接地址: http://www.djcxy.com/p/21566.html

上一篇: SHA512与Blowfish和Bcrypt

下一篇: 我怎样才能生成MD5哈希?