Java的简单MD5加密【JavaEye.2009-10-28】

/** 
* MD5加密运算
* @param str 要加密的字符串,不为null
* @return result 加密后的MD5值
*/
public String getMD5(String str){
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");

messageDigest.reset(); // 重置,供再次使用 messageDigest.update(str.getBytes("UTF-8")); // 使用指定的字节数组更新摘要,Char[]为编码为UTF-8 } catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

byte[] byteArr = messageDigest.digest(); // 重置摘要,通过诸如填充之类的最终操作完成哈希计算 StringBuffer md5Buffer = new StringBuffer(); // 构造一个字符串缓冲区,通过Append追加,装载加密后的值 /*
* 下面涉及到位运算,不懂,研究中。。。
*/
for (int i = 0; i < byteArr.length; i++) {
if (Integer.toHexString(0xFF & byteArr[i]).length() == 1) {
md5Buffer.append("0").append(Integer.toHexString(0xFF & byteArr[i]));
} else {
md5Buffer.append(Integer.toHexString(0xFF & byteArr[i]));
}
}

String result = md5Buffer.toString(); // 从缓冲区得到运算结果 return result;


}



posted @ 2009-10-28 11:36  Mr.Fan  阅读(108)  评论(0)    收藏  举报