架构师训练营第十一周作业

用户头像
Melo
关注
发布于: 2020 年 08 月 24 日

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



import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class checkCredentials {
public static boolean checkPassword(String userId, String pwdPlainText, String pwdEncryptedText) {
if (userId == null || pwdEncryptedText == null || pwdPlainText == null) {
return false;
}
return pwdEncryptedText.equals(encode(userId, pwdPlainText, "MD5"));
}
private static String encode(String userId, String plainText, String hashAlgorithm) {
// encryption algorithm
String concatenatedInput = userId + plainText;
byte[] plainTextWithSaltBytes = concatenatedInput.getBytes();
try {
MessageDigest md = MessageDigest.getInstance(hashAlgorithm);
md.update(plainTextWithSaltBytes);
byte[] encodedInput = md.digest();
BigInteger bigInt = new BigInteger(1, encodedInput);
StringBuilder hashText = new StringBuilder(bigInt.toString(16));
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashText.length() < 32 ){
hashText.insert(0, "0");
}
return new String(hashText);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String userID = "admin";
String plainText = "carmelo";
String encryptedText = "7225cf3eab8ce407bcb5376e2a2f2028";
if (checkPassword(userID, plainText, encryptedText)) {
System.out.println("Password Match");
} else {
System.out.println("Username or Password Error!");
}
}
}



用户头像

Melo

关注

还未添加个人签名 2019.09.17 加入

还未添加个人简介

评论

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