有时候我们经常会使用MD5算法来签名一些字符,下面记录一下Java实现的最简单MD5算法:
注意,如下这种方法会在MD5串第一位为0 的时候不显示,这是一个大坑,推荐用第二个。
public class MD5 {
/**
* 对字符串进行MD5加密
* @param str 需要加密的字符串
* @return 小写MD5字符串 32位
*/
public static String encode(String str) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.update(str.getBytes());
return new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
下面才是正确的方法
/**
* md5加密,32位小写结果
* */
public static String md5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] btInput = s.getBytes("UTF-8");
MessageDigest mdInst = MessageDigest.getInstance("MD5");
mdInst.update(btInput);
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}