方法0:
public static String MD5(String string) {
if (null != string && !"".equals(string)) {
StringBuffer sb = new StringBuffer();
try {
MessageDigest md5 = MessageDigest.getInstance("Md5");
byte[] bytes = md5.digest(string.getBytes("UTF-8"));
for (int i = 0; i < bytes.length; i++) {
int value = bytes[i] & 0xff;
if (value < 16) {
sb.append("0");
}
sb.append(Integer.toHexString(value));
}
string = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return string;
}
方法1:
public static String Md5(String str) {
if (null != str && !"".equals(str)) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f' };
byte[] md5Byte = md5.digest(str.getBytes("UTF8"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < md5Byte.length; i++) {
sb.append(HEX[(int) (md5Byte[i] & 0xff) / 16]);
sb.append(HEX[(int) (md5Byte[i] & 0xff) % 16]);
}
str = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return str;
}