Shiro之密码加密
前言
Apache Shiro 是 Java 的一个安全框架。目前,使用 Shiro 的人越来越多,因为它相当简单,对比Spring Security,可能没有 Spring Security 做的功能强大,但是在很多项目的实际开发中可能并不需要那么复杂的东西,所以使用小而简单的 Shiro 就足够了。
CredentialsMatcher
在Shiro安全框架中的CredentialsMatcher接口是一个用于密码加密以及对比验证。在用户登录时在用户认证/授权时进行,加密对比。
在使用Shiro框架如果要使用CredentialsMatcher。需要设置好加密类型、加密次数、并注入到Bean中。或通过Security Managem(安全管理员)注入到Bean中。
注册加密
我们使用了Shiro安全框架即可以通过Shiro的内部实现加密的SimpleHash类对注册的密码进行加密。SimpleHash类实现了多个构造函数。注册完成后将用户持久化到数据库中。
注入加密接口方法一
自定义(Realm)域、在域中重写setCredentialsMatcher方法。通过实例化HashedCredentialsMatcher(CredentialsMatcher的子类)定义加密类型和次数,传入(Realm)域中。由Security Manager管理器传入Bean中
@Override public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) { HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(); matcher.setHashAlgorithmName("md5"); matcher.setHashIterations(1024); super.setCredentialsMatcher(matcher); }
注入加密接口方法二
直接在Config配置文件中注入Bean组件。将HashedCredentialsMatcher类直接注入到Bean和Realm(域)中,效果与方法一类似。
@Bean public HashedCredentialsMatcher hashedCredentialsMatcher(){ HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); // 使用md5 算法进行加密 hashedCredentialsMatcher.setHashAlgorithmName("md5"); // 设置散列次数: 意为加密几次 hashedCredentialsMatcher.setHashIterations(1024); return hashedCredentialsMatcher; } @Bean(name = "realm") public Realm getRealm(){ MyRealm myRealm = new MyRealm(); myRealm.setCredentialsMatcher(credentialsMatcher); return myRealm; }
对比加密密码认证/授权
通过重写继承AuthorizingRealm抽象类实现认证和授权。第一种加密注册是在AuthenticatingRealm抽象类中。而AuthorizingRealm抽象类也是继承了AuthenticatingRealm抽象类
当加密功能开启后在AuthenticationInfo认证的方法中会自动将用户密码和加盐进行加密与Subject主体进行比较
加盐(二次加密)
加盐加密是一种对系统登录口令的加密方式,它实现的方式是将每一个口令同一个叫做”盐“(salt)的n位随机数相关联。在注册时给用户添加盐进行二次加密让用户更加安全。