写点什么

架构师训练营十一周作业

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

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

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
public class UserPasswordService {
private static final char[] HEX_DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
private Optional<String> encryptByMD5(String password, String salt) {
if(password == null || password.isEmpty()) throw new IllegalArgumentException("password cannot be null");
if(salt == null || salt.isEmpty()) throw new IllegalArgumentException("salt cannot be null");
String original = password + salt;
byte[] originalBytes = original.getBytes();
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(originalBytes);
// 获得密文
byte[] md5Bytes = md5.digest();
// 把密文转换成十六进制的字符串形式
int len = md5Bytes.length;
char[] str = new char[len * 2];
int k = 0;
for (byte byte0 : md5Bytes) {
str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf];
str[k++] = HEX_DIGITS[byte0 & 0xf];
}
return Optional.of(new String(str));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return Optional.empty();
}
}
public boolean checkPW(String userId, String password, String encryptedPassword) {
//use user id as salt
Optional<String> optional = this.encryptByMD5(password, userId);
return optional.map(s -> s.equals(encryptedPassword)).orElse(false);
}
}



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

sunnywhy

关注

还未添加个人签名 2019.04.25 加入

还未添加个人简介

评论

发布
暂无评论
架构师训练营十一周作业