Shiro 集成 Spring 之加密

本章我们来讲解,如果使用 Shiro 集成 Spring 后,使用加密功能。本章基础代码为上一章 : Shiro 集成 Spring 中的代码。

我们这里演示使用 md5 散列算法进行加密, 并用 TestSalt 作为盐。

首先导入上一章的代码,然后修改 spring-shiro.xml ,添加内容:

1
2
3
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5" />
</bean>

然后将此凭证匹配器 credentialsMatcher 注入到 Realm 中 :

1
2
3
<bean id="myRealm" class="im.zhaojun.realm.MyRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>

并在 Realm 中的 doGetAuthenticationInfo 方法里添加盐的配置 :

1
2
3
4
5
6
7
8
9
10
11
12
13
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {

System.out.println("MyRealm doGetAuthenticationInfo...");

String username = (String) authenticationToken.getPrincipal();
User user = selectUserByUserName(username);
if (user == null) {
throw new UnknownAccountException("当前账户不存在");
}
return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes("TestSalt"), super.getName());
}

既然为 Relam 配置了凭证匹配器,那么就应该把我们存储的密码也进行加密,原始我们的密码为 123456,这里我们使用 md5 散列算法进行加密,并使用 TestSalt 作为 :

1
2
3
4
5
6
7
8
public class GenerateHash {
public static void main(String[] args) {
Md5Hash md5Hash = new Md5Hash("123456", ByteSource.Util.bytes("TestSalt"));
System.out.println(md5Hash.toString());
}
}

// 输出结果为 e5f728a966d050296c428290c9160dda

然后我们将 Realm 中获取的密码改为加密后的值 e5f728a966d050296c428290c9160dda :

1
2
3
4
5
6
private User selectUserByUserName(String username) {
if ("zhao".equals(username)) {
return new User(username, "e5f728a966d050296c428290c9160dda");
}
return null;
}

同上一章,运行项目,进行登陆测试,即可检验结果。

本章代码地址 : https://github.com/zhaojun1998/Premission-Study/tree/master/Permission-Shiro-06/

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/shiro-06/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!