importjava.security.MessageDigest;
publicclassPassword {
//十六进制下数字到字符的映射数组
privatefinalstaticString[] hexDigits ={"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
publicstaticString createPassword(String inputString){
returnencodeByMD5(inputString);
}
publicstaticbooleanauthenticatePassword(String password, String inputString) {
if(password.equals(encodeByMD5(inputString))) {
returntrue;
}else{
returnfalse;
}
}
privatestaticString encodeByMD5(String originString) {
if(originString !=null) {
try{
//创建具有指定算法名称的信息摘要
MessageDigest md =MessageDigest.getInstance("MD5");
//使用指定的字节数组对摘要进行最后更新,然后完成摘要计算
byte[] results =md.digest(originString.getBytes());
//将得到的字节数组变成字符串返回
String resultString =byteArrayToHexString(results);
returnresultString.toUpperCase();
}catch(Exception ex) {
ex.printStackTrace();
}
}
returnnull;
}
privatestaticString byteArrayToHexString(byte[] b) {
StringBuffer resultSb =newStringBuffer();
for(inti =0; i <</span>b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
returnresultSb.toString();
}
privatestaticString byteToHexString(byteb) {
intn =b;
if(n <</span>0)
n =256+n;
intd1 =n /16;
intd2 =n %16;
returnhexDigits[d1] +hexDigits[d2];
}
publicstaticvoidmain(String[] args) {
String password =Password.createPassword("888888");
System.out.println("对888888用MD5摘要后的字符串:"+password);
String inputString ="8888";
System.out.println("8888与密码匹配?"+
Password.authenticatePassword(password, inputString));
inputString ="888888";
System.out.println("888888与密码匹配?"+
Password.authenticatePassword(password, inputString));
}
}
输出结果:
对123456用MD5摘要后的字符串:E10ADC3949BA59ABBE56E057F20F883E
1234与密码匹配?false
123456与密码匹配?true