package com.data;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
public class Md5Test {
/***
* 当前用户ID
*/
static String cUserId = "zhangsan";
public static void main(String[] args) {
Boolean flag = checkPW("zhangsan","123456","e10adc3949ba59abbe56e057f20f883e");
if(flag){
System.out.println("用户名密码相同");
}else{
System.out.println("用户名密码不同");
}
}
/**
* 密码校验函数
* @param userId 用户ID
* @param pwd 密码明文
* @param security 密码密文
* @return
*/
public static Boolean checkPW(String userId,String pwd, String security){
if(Objects.equals(userId,cUserId) && Objects.equals(getMD5(pwd),security)){
return true;
}else{
return false;
}
}
/**
* 获取MD5
* @param plainText 元字符串
* @return 返回字符串
*/
public static String getMD5(String plainText) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");//获取MD5实例
md.update(plainText.getBytes());//此处传入要加密的byte类型值
byte[] digest = md.digest();//此处得到的是md5加密后的byte类型值
int i;
StringBuilder sb = new StringBuilder();
for (int offset = 0; offset < digest.length; offset++) {
i = digest[offset];
if (i < 0)
i += 256;
if (i < 16)
sb.append(0);
sb.append(Integer.toHexString(i));//通过Integer.toHexString方法把值变为16进制
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
评论