• shiro学习三


    由于密码的特殊性:

    通常需要对密码 进行散列,常用的有md5、sha, 

    对md5密码,如果知道散列后的值可以通过穷举算法,得到md5密码对应的明文。

    建议对md5进行散列时加salt(盐),进行加密相当 于对原始密码+盐进行散列。

    正常使用时散列方法:

    在程序中对原始密码+盐进行散列,将散列值存储到数据库中,并且还要将盐也要存储在数据库中。

    如果进行密码对比时,使用相同 方法,将原始密码+盐进行散列,进行比对。

    加密代码示例:

    //原始 密码
            String source = "111111";
            //
            String salt = "qwerty";
            //散列次数
            int hashIterations = 2;
            //上边散列1次:f3694f162729b7d0254c6e40260bf15c
            //上边散列2次:36f2dfa24d0a9fa97276abbe13e596fc
            Md5Hash md5Hash = new Md5Hash(source, salt, hashIterations);
    
            //构造方法中:
            //第一个参数:明文,原始密码
            //第二个参数:盐,通过使用随机数
            //第三个参数:散列的次数,比如散列两次,相当 于md5(md5(''))
            String password_md5 = md5Hash.toString();
            System.out.println(password_md5);
            //第一个参数:散列算法
            SimpleHash simpleHash = new SimpleHash("md5", source, salt, hashIterations);
            System.out.println(simpleHash);

    实际开发时realm要进行md5值(明文散列后的值)的对比。

    1、进行realm配置

    [main]
    #凭证匹配器
    credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
    #散列算法
    credentialsMatcher.hashAlgorithmName=md5
    #散列次数
    credentialsMatcher.hashIterations=1
    
    #将凭证匹配器设置给realm
    customRealm=shiro.realm.CustomRealmMd5
    customRealm.credentialsMatcher=$credentialsMatcher
    securityManager.realms=$customRealm

    2、在realm中进行比对

        //用于认证
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
            //token是用户输入的,
            //第一步,从token中取出身份信息
            String userCode = (String) token.getPrincipal();
            //第二部,根据用户输入的userCode从数据库查询
            //。。。。
            
            //未查到
            /*if(!userCode.equals("")){
                return null;
            }*/
            
            //模拟从数据库中查到密码
            String password = "36f2dfa24d0a9fa97276abbe13e596fc";//查到加密后的散列值
            String salt = "qwerty";
    
    
    
            //查询不到返回null
            //查到了返回认证信息AuthenticationInfo
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userCode, password, ByteSource.Util.bytes(salt),this.getName());
    
    
            return authenticationInfo;
        }
  • 相关阅读:
    Hadoop第一天
    Python第二天-字典类型的基本使用讲解
    Python第二天-元组的基本使用方法
    Python第二天-list基本功能详解
    Python第一天-str基本功能详解与测试
    while循环
    用户输入
    字典
    if语句
    运算符
  • 原文地址:https://www.cnblogs.com/xcggdd/p/7295945.html
Copyright © 2020-2023  润新知