Shiro笔记(四)编码/加密

一、编码和解码

     //base64编码、解码
@Test
public void testBase64(){
String str="tang";
byte[] encode = Base64.encode(str.getBytes());
System.out.println("Encode result:"+encode);
System.out.println("The decode result:"+Base64.decodeToString(encode));
} //16进制字符串编码,解码
@Test
public void testHex(){
String str="Java";
char[] encode = Hex.encode(str.getBytes());
System.out.println("encode result:"+encode);
System.out.println("decode result:"+new String(Hex.decode(encode)));
}

二、散列算法

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

     //MD5算法
@Test
public void testMD5(){
String str="king";
String salt="salt1";
String s = new Md5Hash(str, salt).toString();
System.out.println("MD5 code: "+s);
} //SHA算法
@Test
public void testSHA(){
String str="king";
String salt="salt1";
String s = new Sha256Hash(str, salt).toString();
System.out.println("SHA code: "+s);
}

三、PasswordService/CredentialMatcher

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

 public interface PasswordService {

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

     //匹配用户输入的 token 的凭证(未加密)与系统提供的凭证(已加密)
boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info); }

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

应用实例:

 public class MyRealm extends AuthorizingRealm{

     private PasswordService passwordService;

     public void setPasswordService(PasswordService passwordService) {
this.passwordService = passwordService;
} protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
} protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
return new SimpleAuthenticationInfo("tang",
passwordService.encryptPassword("123456"),getName());
}
}

HashedCredentialsMatcher应用:

 public class MyRealm2 extends AuthorizingRealm {

     @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
} @Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = "liu"; //用户名及salt1
String salt2 = "0072273a5d87322163795118fdd7c45e";
String password = "be320beca57748ab9632c4121ccac0db"; //加密后的密码
SimpleAuthenticationInfo ai = new SimpleAuthenticationInfo(username, password, getName());
ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); //盐是用户名+随机数
return ai;
}
}

四、密码重试次数限制

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

 public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

     private Ehcache passwordRetryCache;

     public RetryLimitHashedCredentialsMatcher() {
CacheManager cacheManager = CacheManager.newInstance(CacheManager.class.getClassLoader().getResource("ehcache.xml"));
passwordRetryCache = cacheManager.getCache("passwordRetryCache");
} @Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
String username = (String)token.getPrincipal();
//retry count + 1
Element element = passwordRetryCache.get(username);
if(element == null) {
element = new Element(username , new AtomicInteger(0));
passwordRetryCache.put(element);
}
AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();
if(retryCount.incrementAndGet() > 5) {
//if retry count > 5 throw
throw new ExcessiveAttemptsException();
} boolean matches = super.doCredentialsMatch(token, info);
if(matches) {
//clear retry count
passwordRetryCache.remove(username);
}
return matches;
}
}
 <?xml version="1.0" encoding="UTF-8"?>
<ehcache name="es"> <diskStore path="java.io.tmpdir"/> <!-- 登录记录缓存 锁定10分钟 -->
<cache name="passwordRetryCache"
maxEntriesLocalHeap="2000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="false"
statistics="true">
</cache> </ehcache>

Shiro笔记(四)编码/加密的更多相关文章

  1. 跟开涛老师学shiro -- 编码/加密

    在涉及到密码存储问题上,应该加密/生成密码摘要存储,而不是存储明文密码.比如之前的600w csdn账号泄露对用户可能造成很大损失,因此应加密/生成不可逆的摘要方式存储. 5.1 编码/解码 Shir ...

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

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

  3. Java加密与解密笔记(二) 对称加密

    前面的仅仅是做了编码或者摘要,下面看看真正的加密技术. DES public class DESUtil { static final String ALGORITHM = "DES&quo ...

  4. [AS3]as3用ByteArray来对SWF文件编码加密实例参考

    [AS3]as3用ByteArray来对SWF文件编码加密实例参考,简单来说,就是将 swf 以 binary 的方式读入,并对 ByteArray 做些改变,再重新存成 swf 档.这个作业当然也可 ...

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

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

  6. Shiro笔记(一)基本概念

    Shiro笔记(一)基本概念 一.简介 Shiro是一个Java安全框架,可以帮助我们完成:认证.授权.加密.会话管理.与Web集成.缓存等. Authentication:身份认证/登录,验证用户是 ...

  7. python3.4学习笔记(四) 3.x和2.x的区别,持续更新

    python3.4学习笔记(四) 3.x和2.x的区别 在2.x中:print html,3.x中必须改成:print(html) import urllib2ImportError: No modu ...

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

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

  9. 《MFC游戏开发》笔记四 键盘响应和鼠标响应:让人物动起来

    本系列文章由七十一雾央编写,转载请注明出处. http://blog.csdn.net/u011371356/article/details/9327377 作者:七十一雾央 新浪微博:http:// ...

随机推荐

  1. 【转】Windows下安装python2和python3双版本

    [转]Windows下安装python2和python3双版本 现在大家常用的桌面操作系统有:Windows.Mac OS.ubuntu,其中Mac OS 和 ubuntu上都会自带python.这里 ...

  2. UML和模式应用5:细化阶段(1)--第1次迭代

    1.前言 从本文开始进入细化阶段,讨论迭代技术的基础,本次讨论将着重讨论第一次迭代,以POS机为例. 2. 第一次迭代处理的需求(以NextGen POS项目处理销售用例) 实现 处理销售 用例中基本 ...

  3. linux系统下安装redis及配置

    下载Redis redis-3.2.11.tar.gz 解压编译 tar xzf redis-3.2.11.tar.gz cd redis-3.2.11 make 编译完成之后,可以看到解压文件red ...

  4. Expm 4_2 有向无环图中的最短路径问题

    [问题描述] 建立一个从源点S到终点E的有向无环图,设计一个动态规划算法求出从S到E的最短路径值,并输出相应的最短路径. 解: package org.xiu68.exp.exp4; import j ...

  5. 在Linux上安装go-gtk

    由于Linux的Gnome桌面就是用GTK编写的,所以,Linux本身就包含GTK工具库,安装GTK工具库在线安装即可. 第一步:在终端输入: sudo apt-get install libgtk3 ...

  6. 用jquery添加新元素很容易,面对jquery append 动态添加的元素事件on 不起作用我们该如何解决呢?

    用jquery添加新元素很容易,面对jquery append 动态添加的元素事件on 不起作用我们该如何解决呢?on方法中要先找到原选择器(如例.info),再找到动态添加的选择器(如列.delet ...

  7. 将数据库从Oracle迁移到SQL Server

    参考链接:http://www.360doc.com/content/15/0310/14/9260775_454038517.shtml

  8. 关于z-index的那些事儿

    关于z-index的真正问题是,很少有人理解它到底是怎么用.其实它并不复杂,但是如果你从来没有花一定时间去看具体的z-index相关文档,那么你很可能会忽略一些重要的信息. 不相信我吗?好吧,看看你能 ...

  9. Windows下安装并启动mongodb

    一.Windows下mongodb的安装 MongoDB 提供了可用于 32 位和 64 位系统的预编译二进制包,你可以从MongoDB官网下载安装,MongoDB 预编译二进制包下载地址:https ...

  10. 设计模式【转自JackFrost的博客】

    首先,感谢作者对知识的分享 使用设计模式是为了可重用代码.让代码更容易被他人理解.保证代码可靠性.设计模式使代码编制真正工程化,是软件工程的基石脉络,如同大厦的结构一样. 文章结构:1.单一职责原则( ...