MD5加密

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * 該類的功能是對密碼進行MD5算法摘要
 * @author :趙本兵
 * @創建時間:2011-7-29
 */
public class MD5Util {
public static final int LENGTH = 16;
/**
* 該方法將指定的字符串用MD5算法加密後返回。
* @param str 需要加密的字符串
* @return 返回32位字符串
*/
public static  String getMD5Encoding(String str){
byte[] input = str.getBytes();
String output = null;
//聲明16進制字母
char[] hexChar={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
try {
//MD5摘要算法
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input);
//MD5算法的結果是128位一個整數,在這裏javaAPI已經把結果轉換成字節數組了 
byte[] temp = md.digest();
char[] ch = new char[32];
byte b = 0;
for (int i = 0; i < LENGTH; i++) {
b = temp[i];
//取每一個字節的低四位換成16進制字母 
ch[2*i] = hexChar[b>>>4&0xf];
//取每一個字節的高四位換成16進制字母 
ch[2*i+1] = hexChar[b&0xf];
}
output = new String(ch);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();

return output;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章