当前位置:   article > 正文

SpringBoot+Spring Security验证密码MD5加密_springboot springsecurity配置md5加密

springboot springsecurity配置md5加密

本文目的:使用springBoot+springSecurity 用户授权验证权限功能,对用户的登录密码使用MD5 加密。

本文基于我的博客:springboot+mybatis+SpringSecurity 实现用户角色数据库管理 
进行修改。

本文只讲述对密码加密部分。只需要修改securityConfig 文件,并添加md5 工具类即可。


修改WebSecurityConfig.java

对于WebSecurityConfig.Java 文件只需修改configure(AuthenticationManagerBuilder auth) 方法。

  1. @Override
  2. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  3. auth.userDetailsService(customUserService()).passwordEncoder(new PasswordEncoder(){
  4. @Override
  5. public String encode(CharSequence rawPassword) {
  6. return MD5Util.encode((String)rawPassword);
  7. }
  8. @Override
  9. public boolean matches(CharSequence rawPassword, String encodedPassword) {
  10. return encodedPassword.equals(MD5Util.encode((String)rawPassword));
  11. }}); //user Details Service验证
  12. }

 

添加MD5工具类

  1. package com.us.example.util;
  2. /**
  3. * Created by yangyibo on 17/2/7.
  4. */
  5. import java.security.MessageDigest;
  6. /**
  7. * MD5加密工具
  8. *
  9. */
  10. public class MD5Util {
  11. private static final String SALT = "tamboo";
  12. public static String encode(String password) {
  13. password = password + SALT;
  14. MessageDigest md5 = null;
  15. try {
  16. md5 = MessageDigest.getInstance("MD5");
  17. } catch (Exception e) {
  18. throw new RuntimeException(e);
  19. }
  20. char[] charArray = password.toCharArray();
  21. byte[] byteArray = new byte[charArray.length];
  22. for (int i = 0; i < charArray.length; i++)
  23. byteArray[i] = (byte) charArray[i];
  24. byte[] md5Bytes = md5.digest(byteArray);
  25. StringBuffer hexValue = new StringBuffer();
  26. for (int i = 0; i < md5Bytes.length; i++) {
  27. int val = ((int) md5Bytes[i]) & 0xff;
  28. if (val < 16) {
  29. hexValue.append("0");
  30. }
  31. hexValue.append(Integer.toHexString(val));
  32. }
  33. return hexValue.toString();
  34. }
  35. public static void main(String[] args) {
  36. System.out.println(MD5Util.encode("abel"));
  37. }
  38. }

 

数据库

使用MD5 加密后,数据库中存储的密码应该是加密后的密码

这里写图片描述

本文完整代码:https://github.com/527515025/springBoot

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/922010
推荐阅读
相关标签
  

闽ICP备14008679号