强密码策略+使用jasypt保存用户密码
1.强密码策略:
至少12个字符; 大小写字母、数字和特殊字符等混合使用;
大小写字母 数字 特殊字符都要有.
示例代码
/*** @Description 生成随机密码* @Author hanyc* @Date 2023/4/17*/
public class RandomUtil {private static final char[] CHARS = new char[]{'a', 'b', 'c', 'd', 'e','f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U','V', 'W', 'X', 'Y', 'Z'};private static final char[] CHARS_DIGIT = new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};private static final char[] CHARS_SYMBOL = new char[]{'!', '@', '#', '*', '-'};/*** 生成随机字符串,包含数字和字母** @param length 字母长度* @param digitLength 数字和字符长度* @return 随机字符串* @author zmr*/public static String randomStr(int length, int digitLength) {return RandomStringUtils.random(length, CHARS) + RandomStringUtils.random(digitLength, CHARS_SYMBOL) + RandomStringUtils.random(digitLength, CHARS_DIGIT);}public static void main(String[] args) {System.out.println(randomStr(8, 2));}
}
2.密码第三方工具包建议 jasypt
jasypt说明:
Jasypt(Java Simplified Encryption)是一个专注于简化Java加密操作的工具。 它提供了一种简单而强大的方式来处理数据的加密和解密,使开发者能够轻松地保护应用程序中的敏感信息,如数据库密码、API密钥等。 Jasypt的设计理念是简化加密操作,使其对开发者更加友好。
ps:下方示例代码中 相同明文加密 每次生成的秘钥都不同.
maven依赖
|
java工具类代码
/*** 密码加密/验证工具类** @author hanyc* @date 2024-09-10*/
public class PasswordUtil {/*** 加盐字符串*/private static final String SALT_STR = "gkza";/*** 账号密码加密*/public static String encodePwd(String password) {password = SALT_STR + password;// 创建一个 StandardStringDigester 实例StandardStringDigester digester = new StandardStringDigester();// 添加盐值digester.setSaltSizeBytes(16);// 设置算法为 SHA-256(或者其他你需要的算法)digester.setAlgorithm("SHA-256");// 设置迭代次数(增加安全性)digester.setIterations(1000);// 执行摘要加密return digester.digest(password);}/*** 账号密码验证是否一致** @param password 秘钥* @param digest 加密后的文本* @return*/public static Boolean matches(String password, String digest) {password = SALT_STR + password;// 创建一个 StandardStringDigester 实例StandardStringDigester digester = new StandardStringDigester();// 添加盐值digester.setSaltSizeBytes(16);// 设置算法为 SHA-256(或者其他你需要的算法)digester.setAlgorithm("SHA-256");// 设置迭代次数(增加安全性)digester.setIterations(1000);// 验证摘要是否匹配return digester.matches(password, digest);}public static void main(String[] args) {// 相同明文加密 每次生成的秘钥都不同.String password = "istic12345";String format = encodePwd(password);String format2 = encodePwd(password);System.out.println(format);System.out.println(format2);System.out.println(matches(password, format).toString());System.out.printf(matches(password, format2).toString());}
}