一道加密算法题
2020-08-28 本文已影响0人
花生无翼
请用你熟悉的编程语言写一个用户密码验证函数,Boolean checkPW(String 用户 ID,String 密码明文,String 密码密文)返回密码是否正确 boolean 值,密码加密算法使用你认为合适的加密算法。
package com.ssm.simple.demo.algorithm;
import org.apache.commons.codec.binary.Hex;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 验证用户密码
*
* @Author peanutnowing
* @Date 2020/8/26
*/
public class CheckPWDemo {
/**
* 密码验证
* @param userId
* @param password
* @param encodedPassword
* @return
* @throws NoSuchAlgorithmException
*/
public static Boolean checkPW(String userId, String password, String encodedPassword) throws NoSuchAlgorithmException {
String encryptedStr = encodeBySHA256(userId+password);
return encodedPassword.equals(encryptedStr);
}
/**
* 加密
* @param str
* @return
* @throws NoSuchAlgorithmException
*/
private static String encodeBySHA256(String str) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte[] digestBytes = messageDigest.digest(str.getBytes());
String digestStr = Hex.encodeHexString(digestBytes);
return digestStr;
}
public static void main(String[] args) throws NoSuchAlgorithmException {
String userId = "10001";
String pwd = "asdf1234";
System.out.println(encodeBySHA256(userId+pwd));
Boolean result = checkPW(userId, pwd, encodeBySHA256(userId+pwd));
System.out.printf("result:"+ result);
}
}