PasswordUtil.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.zhentao.util;
  2. import org.springframework.stereotype.Component;
  3. import org.springframework.util.DigestUtils;
  4. import java.nio.charset.StandardCharsets;
  5. import java.security.SecureRandom;
  6. import java.util.Base64;
  7. /**
  8. * 密码加密工具类
  9. * 使用MD5(密码+盐)的方式加密
  10. */
  11. @Component
  12. public class PasswordUtil {
  13. /**
  14. * 生成随机盐(32位)
  15. *
  16. * @return 盐字符串
  17. */
  18. public String generateSalt() {
  19. SecureRandom random = new SecureRandom();
  20. byte[] saltBytes = new byte[16];
  21. random.nextBytes(saltBytes);
  22. return Base64.getEncoder().encodeToString(saltBytes).substring(0, 32);
  23. }
  24. /**
  25. * 加密密码
  26. * 加密方式:MD5(密码 + 盐)
  27. *
  28. * @param password 原始密码
  29. * @param salt 盐
  30. * @return 加密后的密码
  31. */
  32. public String encryptPassword(String password, String salt) {
  33. if (password == null || salt == null) {
  34. throw new IllegalArgumentException("密码和盐不能为空");
  35. }
  36. String passwordWithSalt = password + salt;
  37. return DigestUtils.md5DigestAsHex(passwordWithSalt.getBytes(StandardCharsets.UTF_8));
  38. }
  39. /**
  40. * 验证密码
  41. *
  42. * @param inputPassword 用户输入的密码
  43. * @param storedPassword 数据库中存储的加密密码
  44. * @param salt 盐
  45. * @return 是否匹配
  46. */
  47. public boolean verifyPassword(String inputPassword, String storedPassword, String salt) {
  48. if (inputPassword == null || storedPassword == null || salt == null) {
  49. return false;
  50. }
  51. String encryptedPassword = encryptPassword(inputPassword, salt);
  52. return encryptedPassword.equals(storedPassword);
  53. }
  54. }