Java的MD5加密

  1. /** 
  2.  * MD5的算法在RFC1321 中定義 
  3.  * 在RFC 1321中,給出了Test suite用來檢驗你的實現是否正確:  
  4.  * MD5 ("") = d41d8cd98f00b204e9800998ecf8427e  
  5.  * MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661  
  6.  * MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72  
  7.  * MD5 ("message digest") = f96b697d7cb7938d525a2f31aaf161d0  
  8.  * MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b  
  9.  */  

public static String MD5String(String str) {

MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
}
catch (Exception e) {
e.printStackTrace();
return "";
}


char[] charArray = str.toCharArray();
byte[] byteArray = new byte[charArray.length];


for (int i = 0; i < charArray.length; i++) {
byteArray[i] = (byte) charArray[i];
}
byte[] md5Bytes = md5.digest(byteArray); // MD5 的計算結果是一個 128 位的長整數,  


StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();

}


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