Shiro密码加密验证服务

来源:互联网 发布:七月与安生影评知乎 编辑:程序博客网 时间:2024/05/22 10:56

HashedCredentialsMatcher实现密码验证服务

Shiro提供了CredentialsMatcher的散列实现HashedCredentialsMatcher,和之前的PasswordMatcher不同的是,它只用于密码验证,且可以提供自己的盐,而不是随机生成盐,且生成密码散列值的算法需要自己写,因为能提供自己的盐。

 

1、生成密码散列值

此处我们使用MD5算法,“密码+盐(用户名+随机数)”的方式生成散列值:

Java代码  收藏代码
  1. String algorithmName = "md5";  
  2. String username = "liu";  
  3. String password = "123";  
  4. String salt1 = username;  
  5. String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();  
  6. int hashIterations = 2;  
  7.   
  8. SimpleHash hash = new SimpleHash(algorithmName, password, salt1 + salt2, hashIterations);  
  9. String encodedPassword = hash.toHex();   

如果要写用户模块,需要在新增用户/重置密码时使用如上算法保存密码,将生成的密码及salt2存入数据库(因为我们的散列算法是:md5(md5(密码+username+salt2)))


密码重试次数限制

如在1个小时内密码最多重试5次,如果尝试次数超过5次就锁定1小时,1小时后可再次重试,如果还是重试失败,可以锁定如1天,以此类推,防止密码被暴力破解。我们通过继承HashedCredentialsMatcher,且使用Ehcache记录重试次数和超时时间。

 

com.github.zhangkaitao.shiro.chapter5.hash.credentials.RetryLimitHashedCredentialsMatcher:

Java代码  收藏代码
  1. public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {  
  2.        String username = (String)token.getPrincipal();  
  3.         //retry count + 1  
  4.         Element element = passwordRetryCache.get(username);  
  5.         if(element == null) {  
  6.             element = new Element(username , new AtomicInteger(0));  
  7.             passwordRetryCache.put(element);  
  8.         }  
  9.         AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();  
  10.         if(retryCount.incrementAndGet() > 5) {  
  11.             //if retry count > 5 throw  
  12.             throw new ExcessiveAttemptsException();  
  13.         }  
  14.   
  15.         boolean matches = super.doCredentialsMatch(token, info);  
  16.         if(matches) {  
  17.             //clear retry count  
  18.             passwordRetryCache.remove(username);  
  19.         }  
  20.         return matches;  
  21. }   

如上代码逻辑比较简单,即如果密码输入正确清除cache中的记录;否则cache中的重试次数+1,如果超出5次那么抛出异常表示超出重试次数了




原创粉丝点击