06 shiro的密码比对

在了解了shiro中的“记住我”之后,我们接下来再来测试shiro中的密码比对功能。

1、前提约束

  • 完成shiro与spring的整合 https://www.jianshu.com/p/a352b6338833

    2、操作步骤

  • 在applicationContext-shiro.xml中加入以下标签
    <!--凭证管理器-->
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <!--加密方式-->
        <property name="hashAlgorithmName" value="SHA-256"/>
        <!--加密次数-->
        <property name="hashIterations" value="2"/>
    </bean>

    <!--自定义realm-->
    <bean id="userRealm" class="net.wanho.security.MyRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"></property>
    </bean>
  • 在main方法中测试sha256加密【sha256相对md5更加安全】
public static void main(String[] args)
{
        String password = "123456";//要加密的字符串
        String salt = "wanho";//盐
        Integer hashIterations = 2;//散列次数
        //1.不加盐的sha256
        Sha256Hash sha = new Sha256Hash(password);
        System.out.println(sha.toString());
        //2.加盐的sha256
        sha = new Sha256Hash(password, salt);
        System.out.println(sha.toString());
        //3.加盐再设置散列次数的sha256
        sha = new Sha256Hash(password, salt, hashIterations);
        System.out.println(sha.toString());
        //4.利用SimpleHash来设置sha256(上面三种都可以通过这个来设置,这里举例加盐加散列次数的)
        //第一个参数是算法名称,这里指定SHA-256,第二个是要加密的密码,第三个参数是加盐,第四个是散列次数
        SimpleHash hash = new SimpleHash("SHA-256", password, salt,hashIterations);
        System.out.println(hash.toString());//这就是123456基于SHA-256、盐值和散列次数加密的结果P1
}

特别注意:手动将账号ali,密码加密的结果P1,盐值wanho存储数据库

  • 对照xml中的配置修改Realm中的认证方法
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取账号
        String userName = (String) token.getPrincipal();
        //根据用户名称获取用户信息,特别注意一个账号肯定只能获取一条记录,在这条记录当中包含用户名,加密的密码以及盐值。
        //getUser这个方法就是要去查询数据库的。
        User user = getUser(userName);
        //SimpleAuthenticationInfo构造方法的参数意义如下:
        //userName: 账号  即ali
        //user.getPassword(): 数据库中存储的加密的密码 即上面的P1
        //ByteSource.Util.bytes(user.getPasswordSalt()):数据库中存储的盐 即wanho
        //getName(): 当前realm的名称
        SimpleAuthenticationInfo info= new SimpleAuthenticationInfo(userName, user.getPassword(), ByteSource.Util.bytes(user.getPasswordSalt()), getName());
        return info;
    }

以上就是shiro中密码比对的过程。

猜你喜欢

转载自www.cnblogs.com/alichengxuyuan/p/12520000.html
06
今日推荐