Shiro笔记(四)编码/加密

一、编码和解码

 1     //base64编码、解码
 2     @Test
 3     public void testBase64(){
 4         String str="tang";
 5         byte[] encode = Base64.encode(str.getBytes());
 6         System.out.println("Encode result:"+encode);
 7         System.out.println("The decode result:"+Base64.decodeToString(encode));
 8     }
 9
10     //16进制字符串编码,解码
11     @Test
12     public void testHex(){
13         String str="Java";
14         char[] encode = Hex.encode(str.getBytes());
15         System.out.println("encode result:"+encode);
16         System.out.println("decode result:"+new String(Hex.decode(encode)));
17     }

二、散列算法

散列算法一般用于生成数据的摘要信息,是一种不可逆的算法,一般适合存储密码之类的数据,常见的散列算法如MD5,SHA等。

 1     //MD5算法
 2     @Test
 3     public void testMD5(){
 4         String str="king";
 5         String salt="salt1";
 6         String s = new Md5Hash(str, salt).toString();
 7         System.out.println("MD5 code: "+s);
 8     }
 9
10     //SHA算法
11     @Test
12     public void testSHA(){
13         String str="king";
14         String salt="salt1";
15         String s = new Sha256Hash(str, salt).toString();
16         System.out.println("SHA code: "+s);
17     }

三、PasswordService/CredentialMatcher

Shiro 提供了 PasswordService 及 CredentialsMatcher 用于提供加密密码及验证密码服务。

 1 public interface PasswordService {
 2
 3     //输入明文密码得到密文密码
 4     String encryptPassword(Object plaintextPassword) throws IllegalArgumentException;
 5
 6     /**
 7      * @param submittedPlaintext a raw/plaintext password submitted by an end user/Subject.
 8      * @param encrypted          the previously encrypted password known to be associated with an account.
 9      *                           This value is expected to have been previously generated from the
10      *                           {@link #encryptPassword(Object) encryptPassword} method (typically
11      *                           when the account is created or the account's password is reset).
12      * @return {@code true} if the {@code submittedPlaintext} password matches the existing {@code saved} password,
13      *         {@code false} otherwise.
14      * @see ByteSource.Util#isCompatible(Object)
15      */
16     boolean passwordsMatch(Object submittedPlaintext, String encrypted);
17 }

1 public interface CredentialsMatcher {
2
3     //匹配用户输入的 token 的凭证(未加密)与系统提供的凭证(已加密)
4     boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);
5
6 }

Shiro 默认提供了 PasswordService 实现 DefaultPasswordService;CredentialsMatcher 实现
PasswordMatcher 及 HashedCredentialsMatcher(更强大)。

应用实例:

 1 public class MyRealm extends AuthorizingRealm{
 2
 3     private PasswordService passwordService;
 4
 5     public void setPasswordService(PasswordService passwordService) {
 6         this.passwordService = passwordService;
 7     }
 8
 9     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
10         return null;
11     }
12
13     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
14         return new SimpleAuthenticationInfo("tang",
15                 passwordService.encryptPassword("123456"),getName());
16     }
17 }

HashedCredentialsMatcher应用:

 1 public class MyRealm2 extends AuthorizingRealm {
 2
 3     @Override
 4     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
 5         return null;
 6     }
 7
 8     @Override
 9     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
10         String username = "liu"; //用户名及salt1
11         String salt2 = "0072273a5d87322163795118fdd7c45e";
12         String password = "be320beca57748ab9632c4121ccac0db"; //加密后的密码
13         SimpleAuthenticationInfo ai = new SimpleAuthenticationInfo(username, password, getName());
14         ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); //盐是用户名+随机数
15         return ai;
16     }
17 }

四、密码重试次数限制

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

 1 public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {
 2
 3     private Ehcache passwordRetryCache;
 4
 5     public RetryLimitHashedCredentialsMatcher() {
 6         CacheManager cacheManager = CacheManager.newInstance(CacheManager.class.getClassLoader().getResource("ehcache.xml"));
 7         passwordRetryCache = cacheManager.getCache("passwordRetryCache");
 8     }
 9
10     @Override
11     public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
12         String username = (String)token.getPrincipal();
13         //retry count + 1
14         Element element = passwordRetryCache.get(username);
15         if(element == null) {
16             element = new Element(username , new AtomicInteger(0));
17             passwordRetryCache.put(element);
18         }
19         AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();
20         if(retryCount.incrementAndGet() > 5) {
21             //if retry count > 5 throw
22             throw new ExcessiveAttemptsException();
23         }
24
25         boolean matches = super.doCredentialsMatch(token, info);
26         if(matches) {
27             //clear retry count
28             passwordRetryCache.remove(username);
29         }
30         return matches;
31     }
32 }

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <ehcache name="es">
 3
 4     <diskStore path="java.io.tmpdir"/>
 5
 6
 7
 8     <!-- 登录记录缓存 锁定10分钟 -->
 9     <cache name="passwordRetryCache"
10            maxEntriesLocalHeap="2000"
11            eternal="false"
12            timeToIdleSeconds="3600"
13            timeToLiveSeconds="0"
14            overflowToDisk="false"
15            statistics="true">
16     </cache>
17
18 </ehcache>

转载于:https://www.cnblogs.com/Shadowplay/p/7677219.html

Shiro笔记(四)编码/加密相关推荐

  1. Java加密与解密笔记(四) 高级应用

    术语列表: CA:证书颁发认证机构(Certificate Authority) PEM:隐私增强邮件(Privacy Enhanced Mail),是OpenSSL使用的一种密钥文件. PKI:公钥 ...

  2. Java加密与解密笔记(三) 非对称加密

    非对称的特点是加密和解密时使用的是不同的钥匙.密钥分为公钥和私钥,用公钥加密的数据只能用私钥进行解密,反之亦然. 另外,密钥还可以用于数字签名.数字签名跟上文说的消息摘要是一个道理,通过一定方法对数据 ...

  3. Servlet笔记四(JSP技术)

    本栏博客目录 Serlvet笔记一(Servlet基础) Servlet笔记二(请求和响应) Servlet笔记三(会话及其会话技术) Servlet笔记四(JSP技术) Servlet笔记五(EL表 ...

  4. shiro配置盐值加密

    shiro配置盐值加密 一:在shiro配置文件ShiroConfig.java中配置密码凭证匹配器 /*** 密码凭证匹配器,作为自定义认证的基础* @return*/@Beanpublic Has ...

  5. shiro第四讲 JDBC Realm使用 (QQ14280784)

     第一步:进入eclipse新建一个shiro的maven工程 第二步:修改shiro工程的编码为utf-8 第三步:新建一个mysql数据库shiro,在这个数据库 SET FOREIGN_KE ...

  6. 【http学习笔记四】安全篇

    [http学习笔记四]安全篇 文章目录 [http学习笔记四]安全篇 一.HTTPS 与 SSL/TLS ① 什么是安全? 机密性 完整性 身份认证 不可否认 ② 什么是HTTPS? ③ SSL/TL ...

  7. C#可扩展编程之MEF学习笔记(四):见证奇迹的时刻

    前面三篇讲了MEF的基础和基本到导入导出方法,下面就是见证MEF真正魅力所在的时刻.如果没有看过前面的文章,请到我的博客首页查看. 前面我们都是在一个项目中写了一个类来测试的,但实际开发中,我们往往要 ...

  8. IOS学习笔记(四)之UITextField和UITextView控件学习

    IOS学习笔记(四)之UITextField和UITextView控件学习(博客地址:http://blog.csdn.net/developer_jiangqq) Author:hmjiangqq ...

  9. MSSQL编程笔记四 解决count distinct多个字段的方法

    MSSQL编程笔记四 解决count distinct多个字段的方法 参考文章: (1)MSSQL编程笔记四 解决count distinct多个字段的方法 (2)https://www.cnblog ...

  10. RabbitMQ学习笔记四:RabbitMQ命令(附疑难问题解决)

    RabbitMQ学习笔记四:RabbitMQ命令(附疑难问题解决) 参考文章: (1)RabbitMQ学习笔记四:RabbitMQ命令(附疑难问题解决) (2)https://www.cnblogs. ...

最新文章

  1. iOS RunLoop简介
  2. 三个管脚的压电陶瓷片
  3. [Rainy开发笔记]使用RandomAccessFile实现的Tail
  4. org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'PUT' not supported
  5. uni-app 组件传值
  6. bat从数组中找出相同数字并删除_全网把Map中的hash()分析的最透彻的文章,别无二家...
  7. 足不出户带你体验专业实验室,技术实现不在话下
  8. C++新特性探究(十八):智能指针
  9. 1129 Recommendation System
  10. Linux-windows10下安装Ubuntu
  11. JS处理数据四舍五入
  12. 算法:螺旋矩阵算出N行N列的数组Spiral Matrix II
  13. 登录oneNote失败解决
  14. 花絮:用StyleGAN Encoder识别并重建国画和油画中的人脸
  15. vb.net 教程 20-3 控制Ie浏览器 3 获得Ie窗口句柄
  16. PSAM卡相关知识整理
  17. JAVA 导出大批量数据EXCEL
  18. repo的入门和使用
  19. 2015年计算机技术应用大赛,2015年全国大学生先进成图技术与产品信息建模大赛...
  20. DDNS(动态域名解析服务)——让动态的IP固定下来

热门文章

  1. Java并发之Condition接口
  2. Sql语句优化-查询两表不同行NOT IN、NOT EXISTS、连接查询Left Join
  3. Python Django 之 jQuery
  4. 1.Java集合-HashMap实现原理及源码分析
  5. 狭义相对论的一点点理解
  6. discuz核心类库class_core的函数注释
  7. 效果实现JS实现飞雪飘飘的效果
  8. ASIHttpRequest startAsynchronous
  9. 使用ln命令创建软引用(相对路径与绝对路径)
  10. mysql gitd 数据结构同步失败_mysql 5.7 gtid主从同步错误修复