| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package com.zhentao.util;
- import org.springframework.stereotype.Component;
- import org.springframework.util.DigestUtils;
- import java.nio.charset.StandardCharsets;
- import java.security.SecureRandom;
- import java.util.Base64;
- /**
- * 密码加密工具类
- * 使用MD5(密码+盐)的方式加密
- */
- @Component
- public class PasswordUtil {
-
- /**
- * 生成随机盐(32位)
- *
- * @return 盐字符串
- */
- public String generateSalt() {
- SecureRandom random = new SecureRandom();
- byte[] saltBytes = new byte[16];
- random.nextBytes(saltBytes);
- return Base64.getEncoder().encodeToString(saltBytes).substring(0, 32);
- }
-
- /**
- * 加密密码
- * 加密方式:MD5(密码 + 盐)
- *
- * @param password 原始密码
- * @param salt 盐
- * @return 加密后的密码
- */
- public String encryptPassword(String password, String salt) {
- if (password == null || salt == null) {
- throw new IllegalArgumentException("密码和盐不能为空");
- }
- String passwordWithSalt = password + salt;
- return DigestUtils.md5DigestAsHex(passwordWithSalt.getBytes(StandardCharsets.UTF_8));
- }
-
- /**
- * 验证密码
- *
- * @param inputPassword 用户输入的密码
- * @param storedPassword 数据库中存储的加密密码
- * @param salt 盐
- * @return 是否匹配
- */
- public boolean verifyPassword(String inputPassword, String storedPassword, String salt) {
- if (inputPassword == null || storedPassword == null || salt == null) {
- return false;
- }
- String encryptedPassword = encryptPassword(inputPassword, salt);
- return encryptedPassword.equals(storedPassword);
- }
- }
|