06 shiro password comparison

After understanding shiro in the "Remember Me", we come back next test shiro passwords matching capabilities.

1, the premise of restraint

    <!--凭证管理器-->
    <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>
  • In the main test sha256 encryption method [sha256 md5 relatively safer]
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
}

Special attention: manually account ali, password encryption result P1, salt value stored database wanho

  • Xml authentication control method of modifying the configuration of the 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;
    }

These are in the process of shiro password alignment.

Guess you like

Origin www.cnblogs.com/alichengxuyuan/p/12520000.html