写点什么

用户密码验证函数

用户头像
hellohuan
关注
发布于: 2020 年 08 月 26 日

问题描述:请用你熟悉的编程语言写一个用户密码验证函数,Boolean checkPW(String 用户 ID,String 密码明文,String 密码密文)返回密码是否正确 boolean 值,密码加密算法使用你认为合适的加密算法。



首先,确认加密算法为MD5。思路是将用户ID与密码明文组合之后采用MD5加密,将加密得到的字符串与 密码密文做比较,同时返回比较的代码。

加密函数:

public static String encode(String s) {
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
byte[] btInput = s.getBytes("UTF-8");
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[(byte0 >>> 4) & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

用户密码验证函数:

private boolean checkPW(String userId, String origin, String secret){
String encode = MD5Util.encode(userId + origin);
return encode.equals(secret);
}



发布于: 2020 年 08 月 26 日阅读数: 46
用户头像

hellohuan

关注

活到老,学到老 2018.09.17 加入

从事互联网研发工作,对产品、运营充满兴趣,终身学习践行者

评论

发布
暂无评论
用户密码验证函数