当前位置:   article > 正文

项目安全问题及解决方法------使用合适的算法_bcrypt.hashpw(password, hash)

bcrypt.hashpw(password, hash)

Spring Security 已经废弃了 MessageDigestPasswordEncoder,推荐使用 BCryptPasswordEncoder

private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

  1. @GetMapping("performance")
  2. public void performance() {
  3. StopWatch stopWatch = new StopWatch();
  4. String password = "Abcd1234";
  5. stopWatch.start("MD5");
  6. //MD5
  7. DigestUtils.md5Hex(password);
  8. stopWatch.stop();
  9. stopWatch.start("BCrypt(10)");
  10. //代价因子为10的BCrypt
  11. String hash1 = BCrypt.gensalt(10);
  12. BCrypt.hashpw(password, hash1);
  13. System.out.println(hash1);
  14. stopWatch.stop();
  15. stopWatch.start("BCrypt(12)");
  16. //代价因子为12的BCrypt
  17. String hash2 = BCrypt.gensalt(12);
  18. BCrypt.hashpw(password, hash2);
  19. System.out.println(hash2);
  20. stopWatch.stop();
  21. stopWatch.start("BCrypt(14)");
  22. //代价因子为14的BCrypt
  23. String hash3 = BCrypt.gensalt(14);
  24. BCrypt.hashpw(password, hash3);
  25. System.out.println(hash3);
  26. stopWatch.stop();
  27. log.info("{}", stopWatch.prettyPrint());
  28. }

制作 8 位密码长度的 MD5 彩虹表需要 5 个月,那么对于 BCrypt 来说,可能就需要几十年,大部分黑客应该都没有这个耐心。  

  1. @GetMapping("better")
  2. public UserData better(@RequestParam(value = "name", defaultValue = "zhuye") String name, @RequestParam(value = "password", d efaultValue = "Abcd1234")
  3. String password) {
  4. UserData userData = new UserData();
  5. userData.setId(1L);
  6. userData.setId(1L);
  7. userData.setName(name);
  8. //保存哈希后的密码
  9. userData.setPassword(passwordEncoder.encode(password));
  10. userRepository.save(userData);
  11. //判断密码是否匹配
  12. log.info("match ? {}", passwordEncoder.matches(password, userData.getPassword()));
  13. return userData;
  14. }

我们的密码保存方式: "password": "$2a$10$wPWdQwfQO2lMxqSIb6iCROXv7lKnQq5XdMO96iCYCj7boK9pk6QPC" //格式为:$$$ 第一个$后的 2a 代表算法版本,第二个$后的 10 是代价因子(默认是 10,代表 2 的 10 次方次哈希),第三个$后的 22 个字符是盐,再后面是摘要。  

 

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

闽ICP备14008679号