看到之前項(xiàng)目中,關(guān)于MD5加密的足足寫了一個(gè)輔助類,看的都不爽。
其實(shí)在Java中大部分都幫你實(shí)現(xiàn)好了,完成MD5加密,三行代碼足矣:
/**
* 對(duì)字符串md5加密
*
* @param str
* @return
*/
publicstaticStringgetMD5(Stringstr){
try{
// 生成一個(gè)MD5加密計(jì)算摘要
MessageDigestmd=MessageDigest.getInstance("MD5");
// 計(jì)算md5函數(shù)
md.update(str.getBytes());
// digest()最后確定返回md5 hash值,返回值為8為字符串。因?yàn)閙d5 hash值是16位的hex值,實(shí)際上就是8位的字符
// BigInteger函數(shù)則將8位的字符串轉(zhuǎn)換成16位hex值,用字符串來表示;得到字符串形式的hash值
returnnewBigInteger(1,md.digest()).toString(16);
}catch(Exceptione){
thrownewSpeedException("MD5加密出現(xiàn)錯(cuò)誤");
}
}