//錯誤的方式;0xFF & byteArray[i]).length() == 1 的時候會缺少 0 位數不對,
// md5StrBuff.append(Integer.toHexString(0xff & byteArray[i]));
//正確的方式
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
} else {
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
//end
完整的:
import java.security.MessageDigest;
public class MD5Util {
public static void main(String[] args) {
System.out.println(MD5("123"));
}
/**
* 將字符串加密為MD5的結果
* @param source 源字符串
* @return 加密後的字符串
*/
public static String MD5(String source) {
try {
// 對密碼進行MD5加密處理
byte byteEncrypt[] = null;
byteEncrypt = source.getBytes("UTF8");
MessageDigest mdInstance = MessageDigest.getInstance("MD5");
mdInstance.update(byteEncrypt);
byte byteArray[] = mdInstance.digest();
// MD5轉換編碼
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
//錯誤的方式;0xFF & byteArray[i]).length() == 1 的時候會缺少 0 位數不對
// md5StrBuff.append(Integer.toHexString(0xff & byteArray[i]));
//正確的方式
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
} else {
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
//end
}
return md5StrBuff.toString();
} catch (Exception e) {
}
return null;
}
}