代码
package util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashUtil {
private static MessageDigest digest = null;
public synchronized static final String hash(String data) {
if (digest == null) {
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException nsae) {
System.err.println("Failed to load the MD5 MessageDigest. " +
"Jive will be unable to function normally.");
nsae.printStackTrace();
}
}
// Now, compute hash.
digest.update(data.getBytes());
return encodeHex(digest.digest());
}
public static final String encodeHex(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
int i;
for (i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buf.toString();
}
public static final byte[] decodeHex(String hex) {
char[] chars = hex.toCharArray();
byte[] bytes = new byte[chars.length / 2];
int byteCount = 0;
for (int i = 0; i < chars.length; i += 2) {
byte newByte = 0x00;
newByte |= hexCharToByte(chars[i]);
newByte <<= 4;
newByte |= hexCharToByte(chars[i + 1]);
bytes[byteCount] = newByte;
byteCount++;
}
return bytes;
}
private static final byte hexCharToByte(char ch) {
switch (ch) {
case '0':
return 0x00;
case '1':
return 0x01;
case '2':
return 0x02;
case '3':
return 0x03;
case '4':
return 0x04;
case '5':
return 0x05;
case '6':
return 0x06;
case '7':
return 0x07;
case '8':
return 0x08;
case '9':
return 0x09;
case 'a':
return 0x0A;
case 'b':
return 0x0B;
case 'c':
return 0x0C;
case 'd':
return 0x0D;
case 'e':
return 0x0E;
case 'f':
return 0x0F;
}
return 0x00;
}
}
调用
public static void main(String[] args)
{
String pwd = "aabbcc";
String pwdMd5 = HashUtil.hash(pwd);
System.out.println(pwdMd5);
}
输出
61a60170273e74a5be90355ffe8e86ad