JAVA 数据库密码加密(MD5)

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 07:25   36   0

文章出处:http://xxiao0359.blog.163.com/blog/static/979413752010109045701/

import java.security.MessageDigest;




public class Password {

//十六进制下数字到字符的映射数组
private final static String[] hexDigits = {"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"}
;


public static String createPassword(String inputString){
return encodeByMD5(inputString);
}



public static boolean authenticatePassword(String password, String inputString) {
if(password.equals(encodeByMD5(inputString))) {
return true;
}
else {
return false;
}

}



private static String encodeByMD5(String originString) {
if (originString != null) {
try{
//创建具有指定算法名称的信息摘要
MessageDigest md = MessageDigest.getInstance("MD5");
//使用指定的字节数组对摘要进行最后更新,然后完成摘要计算
byte[] results = md.digest(originString.getBytes());
//将得到的字节数组变成字符串返回
String resultString = byteArrayToHexString(results);
return resultString.toUpperCase();
}
catch(Exception ex) {
ex.printStackTrace();
}

}

return null;
}



private static String byteArrayToHexString(byte[] b) {
StringBuffer resultSb
= new StringBuffer();
for (int i = 0; i <</span> b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}

return resultSb.toString();
}



private static String byteToHexString(byte b) {
int n = b;
if (n <</span> 0)
n
= 256 + n;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}


public static void main(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
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP