package com.study; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; public class Md5Test { public static String encodeByMD5(String userPwd){ String pwdByMd5 = ""; try {
MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] bytePwd = md5.digest(userPwd.getBytes()); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < bytePwd.length; i++) {
int val = ((int) bytePwd[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
pwdByMd5 = hexValue.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} return pwdByMd5;
} /**
* 验证输入的密码是否正确
* @param password 加密后的密码
* @param inputString 输入的字符串
* @return 验证结果,TRUE:正确 FALSE:错误
*/
public static boolean validatePassword(String password, String inputString){
if(password.equals(encodeByMD5(inputString))){
return true;
} else{
return false;
}
} }
与 0xff进行&运算 是为了用8字节的byte类型获取一个32字节的int类型数