Shiro学习-密码的比对及密码的MD5加密(八)

密码比对

通过AuthenticatingRealm的credentialsMatcher进行密码的比对
由于你获取数据是从数据库获取的是加密后的密码,所以挺重要的

密码加密

如何把一个字符串加密为MD5
替换当前Realm的CredentialsMatcher属性,可以使用Md5CredentialsMatcher但是推荐使用HashedCredentialsMatcher对象,并设置加密算法

加密的流程

1.为什么使用MD5盐值加密:
2.如何做到:

2.1在doGetAuthenticationInfo方法返回值创建SimpleAuthenticationInfo对象的时候,需要使用SimpleAuthenticationInfo(principal,credentials, credentialSalt,realmName);构造器
2.2 ByteSource.Util.bytes(username); 
2.3盐值需要唯一:一般采用随机字符串和userId
2.4使用new SimpleHash(hashAlgorithmName,credentials,salt,hashIterations)来计算盐值加密后的密码的值
public class ShiroRealm extends AuthenticatingRealm {

//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.将AuthenticationToken转换为UsernamePasswordToken
        UsernamePasswordToken uptoken = (UsernamePasswordToken) token;
        //2.从UsernamePasswordToken获取username
        String username = uptoken.getUsername();
        //3.调用数据库的方法,从数据库中查询username 对应的用户记录
        System.out.println("从数据库中获取该用户名对应的记录");
        //4.若用户不存在,则抛出异常UnknownAccountException
        if(username.equals("qweqw")){
            throw new UnknownAccountException("用户不存在");
        }
        //5.根据用户信息的情况,决定是否抛出其他异常
        if(username.equals("123")){
            throw new LockedAccountException("用户被锁定");
        }
        //6.根据用户的情况,来构建AuthenticationInfo对象并返回,通常使用的实现类为SimpleAuthenticationInfo
        //以下信息是从数据库中获取的
        //1.principal:认证的实体信息,可以是username,也可以是数据表对应的用户的实体类对象
        Object principal = username;
        //2.credentials:密码
        Object credentials = null;
        if("admin".equals(username)){
            credentials = "";  
        }else if("user".equals(username)){
            credentials = "";
        }
        //3.realmName:当前realm对象的name调用父类的getName()方法即可
        String  realmName = getName();
        //4.盐值
        ByteSource credentialSalt= ByteSource.Util.bytes(username); 
        //加密一般使用的是随机字符串或userId

        SimpleAuthenticationInfo info = null;
        info =   new SimpleAuthenticationInfo(principal,credentials, credentialSalt,realmName);
        return info;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Peak_Gao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值