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

5.1 编码/解码

Shiro提供了base64和16进制字符串编码/解码的API支持,方便一些编码解码操作。Shiro内部的一些数据的存储/表示都使用了base64和16进制字符串。

String str = "hello";
String base64Encoded = Base64.encodeToString(str.getBytes());
String str2 = Base64.decodeToString(base64Encoded);
Assert.assertEquals(str, str2); //Junit4中的方法

通过如上方式可以进行base64编码/解码操作,更多API请参考其Javadoc。

String str = "hello";
String hexEncoded = Hex.encodeToString(str.getBytes());
String str2 = new String(Hex.decode(hexEncoded.getBytes()));
Assert.assertEquals(str, str2);

通过如上方式可以进行16进制字符串编码/解码操作,更多API请参考其Javadoc。

还有一个可能经常用到的类CodecSupport,提供了toBytes(str, "utf-8") / toString(bytes, "utf-8")用于在byte数组/String之间转换。

5.2 散列算法

散列算法一般用于生成数据的摘要信息,是一种不可逆的算法,一般适合存储密码之类的数据,常见的散列算法如MD5、SHA等。一般进行散列时最好提供一个salt(盐),比如加密密码“admin”,产生的散列值是“21232f297a57a5a743894a0e4a801fc3”,可以到一些md5解密网站很容易的通过散列值得到密码“admin”,即如果直接对密码进行散列相对来说破解更容易,此时我们可以加一些只有系统知道的干扰数据,如用户名和ID(即盐);这样散列的对象是“密码+用户名+ID”,这样生成的散列值相对来说更难破解。

Shiro还提供了通用的散列支持:

String str = "hello";
String salt = "123";
//内部使用MessageDigest
String simpleHash = new SimpleHash("MD5", str, salt,1024).toString();

通过调用SimpleHash时指定散列算法,其内部使用了Java的MessageDigest实现。

5.4 PasswordService/CredentialsMatcher

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

public interface PasswordService {
//输入明文密码得到密文密码
String encryptPassword(Object plaintextPassword) throws IllegalArgumentException;
}
public interface CredentialsMatcher {
//匹配用户输入的token的凭证(未加密)与系统提供的凭证(已加密)
boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);
}

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

DefaultPasswordService配合PasswordMatcher实现简单的密码加密与验证服务

1、定义Realm

public class MyRealm extends AuthorizingRealm {
private PasswordService passwordService;
public void setPasswordService(PasswordService passwordService) {
this.passwordService = passwordService;
}
//省略doGetAuthorizationInfo,具体看代码
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
return new SimpleAuthenticationInfo(
"wu",
passwordService.encryptPassword("123"),
getName());
}
}

为了方便,直接注入一个passwordService来加密密码,实际使用时需要在Service层使用passwordService加密密码并存到数据库。

2、ini配置(shiro-passwordservice.ini)

[main]
passwordService=org.apache.shiro.authc.credential.DefaultPasswordService
hashService=org.apache.shiro.crypto.hash.DefaultHashService
passwordService.hashService=$hashService
hashFormat=org.apache.shiro.crypto.hash.format.Shiro1CryptFormat
passwordService.hashFormat=$hashFormat
hashFormatFactory=org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory
passwordService.hashFormatFactory=$hashFormatFactory passwordMatcher=org.apache.shiro.authc.credential.PasswordMatcher
passwordMatcher.passwordService=$passwordService myRealm=com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm
myRealm.passwordService=$passwordService
myRealm.credentialsMatcher=$passwordMatcher
securityManager.realms=$myRealm

2.1、passwordService使用DefaultPasswordService,如果有必要也可以自定义;

2.2、hashService定义散列密码使用的HashService,默认使用DefaultHashService(默认SHA-256算法);

2.3、hashFormat用于对散列出的值进行格式化,默认使用Shiro1CryptFormat,另外提供了Base64Format和HexFormat

2.4、hashFormatFactory用于根据散列值得到散列的密码和salt;因为如果使用如SHA算法,那么会生成一个salt,此salt需要保存到散列后的值中以便之后与传入的密码比较时使用;默认使用DefaultHashFormatFactory;

2.5、passwordMatcher使用PasswordMatcher,其是一个CredentialsMatcher实现;

2.6、将credentialsMatcher赋值给myRealm,myRealm间接继承了AuthenticatingRealm,其在调用getAuthenticationInfo方法获取到AuthenticationInfo信息后,会使用credentialsMatcher来验证凭据是否匹配,如果不匹配将抛出IncorrectCredentialsException异常。

HashedCredentialsMatcher实现密码验证服务

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

1.ini配置(shiro-hashedCredentialsMatcher.ini)

[main]
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
credentialsMatcher.hashAlgorithmName=md5
credentialsMatcher.hashIterations=2
credentialsMatcher.storedCredentialsHexEncoded=true
myRealm=com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm2
myRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$myRealm

1、通过credentialsMatcher.hashAlgorithmName=md5指定散列算法为md5,需要和生成密码时的一样;

2、credentialsMatcher.hashIterations=2,散列迭代次数,需要和生成密码时的意义;

3、credentialsMatcher.storedCredentialsHexEncoded=true表示是否存储散列后的密码为16进制,需要和生成密码时的一样,默认是base64;

此处最需要注意的就是HashedCredentialsMatcher的算法需要和生成密码时的算法一样。另外HashedCredentialsMatcher会自动根据AuthenticationInfo的类型是否是SaltedAuthenticationInfo来获取credentialsSalt盐。

2、自定义Realm继承AuthorizingRealm实现doGetAuthenticationInfo方法

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = "liu"; //用户名及salt1
String password = "202cb962ac59075b964b07152d234b70"; //加密后的密码
String salt2 = username ;
   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"));
,r.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());
passwordRetryCache.put(element);
}
AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();
if(retryCount.incrementAndGet() > ) {
//if retry count > 5 throw
throw new ExcessiveAttemptsException();
} boolean matches = super.doCredentialsMatch(token, info);
if(matches) {
//clear retry count
passwordRetryCache.remove(username);
}
return matches;
}
}

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

第五章:shiro密码加密的更多相关文章

  1. Shiro密码加密

    Shiro密码加密 相关类 org.apache.shiro.authc.credential.CredentialsMatcher org.apache.shiro.authc.credential ...

  2. JavaEE权限管理系统的搭建(四)--------使用拦截器实现登录认证和apache shiro密码加密

    RBAC 基于角色的权限访问控制(Role-Based Access Control)在RBAC中,权限与角色相关联,用户通过成为适当角色的成员而得到这些角色的权限.这就极大地简化了权限的管理.在一个 ...

  3. shiro系列五、shiro密码MD5加密

    Shiro-密码的MD5加密   1.密码的加密 在数据表中存的密码不应该是123456,而应该是123456加密之后的字符串,而且还要求这个加密算法是不可逆的,即由加密后的字符串不能反推回来原来的密 ...

  4. Shiro——MD5加密

    一.shiro默认密码的比对 通过 AuthenticatingRealm 的 credentialsMatcher 属性来进行的密码的比对 /**源码org.apache.shiro.realm.A ...

  5. 第五章 编码/加密——《跟我学Shiro》

    转发地址:https://www.iteye.com/blog/jinnianshilongnian-2021439 目录贴:跟我学Shiro目录贴 在涉及到密码存储问题上,应该加密/生成密码摘要存储 ...

  6. Shiro自定义realm实现密码验证及登录、密码加密注册、修改密码的验证

    一:先从登录开始,直接看代码 @RequestMapping(value="dologin",method = {RequestMethod.GET, RequestMethod. ...

  7. Apach Shiro MD5密码加密过程(明文生成密码过程)详细解析

    前言: 最近再项目当中使用的ApachShiro安全框架,对于权限和服务器资源的保护都有一个很好的管理.前期主要参考的文章有 项目中设计密码的加盐处理以及二次加密问题,跟着断点 一步步揭开Apach ...

  8. shiro登录密码加密

    密码加密 String passwd = new SimpleHash("SHA-1", "username", "password").t ...

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

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

随机推荐

  1. Exp6 信息搜集与漏洞扫描 20164312 马孝涛

    1.实践内容 (1)各种搜索技巧的应用  (2)DNS IP注册信息的查询  (3)基本的扫描技术:主机发现.端口扫描.OS及服务版本探测.具体服务的查点(以自己主机为目标)  (4)漏洞扫描:会扫, ...

  2. 关于Redis的常见面试题解析

    1. 使用redis有哪些好处? (1) 速度快,因为数据存在内存中,类似于HashMap,HashMap的优势就是查找和操作的时间复杂度都是O(1) (2) 支持丰富数据类型,支持string,li ...

  3. 操作系统底层原理与Python中socket解读

    目录 操作系统底层原理 网络通信原理 网络基础架构 局域网与交换机/网络常见术语 OSI七层协议 TCP/IP五层模型讲解 Python中Socket模块解读 TCP协议和UDP协议 操作系统底层原理 ...

  4. final 关键字与安全发布 多线程中篇(十三)

    final的通常理解 在Java中,final关键字可以用来修饰类.方法和变量(包括成员变量和局部变量) 大家应该都知道final表示最终的.最后的含义,也就是不能在继续 修饰类表示不能继承,修饰方法 ...

  5. 微服务(入门二):netcore通过consul注册服务

    基础准备 1.创建asp.net core Web 应用程序选择Api 2.appsettings.json 配置consul服务器地址,以及本机ip和端口号信息 { "Logging&qu ...

  6. 关于vue使用form上传文件

    在vue中使用form表单上传文件文件的时候出现了一些问题,获取文件的时候一直返回null, 解决之后又出现发送到后台的file文件后台显示为空,解决源码 <template> <d ...

  7. Git学习:如何在Github的README.MD文件下添加图片

    格式如下: ![image](图片的绝对路径) 关于图片的绝对路径: 必须把图片上传到github的代码仓库里,再将其图片的网址复制到括号里才可以,不能够直接把图片复制到readme.md文件里面,这 ...

  8. ArcMap插件开发初识:Add In

    之前一直在做ArcEngine的相关开发,做的winform相关,新换了工作,又开始新的学习旅程! Add In 这个东西很早就知道有,但是一直没有用过,因为之前的公司有自己框架,接口,虽然我也是做插 ...

  9. 产品经理之PRD详解

    文章大纲 一.PRD基础二.PRD要素讲解三.相关模板下载四.参考文章   一.PRD基础 1. PRD简介    PRD中文意思为:产品需求文档.PRD的主要使用对象有:开发.测试.项目经理.交互设 ...

  10. SQL2005打SP4补丁报错:无法安装Windows Installer MSP文件解决方案

    错误如图: 解决方案分享如下: 第一步:卸载下图红框圈住的玩艺. 第二步:把SP4补丁文件解压,找到下图红框圈住的玩艺: 第三步:重新运行SP4补丁安装文件,安装正常.