java shiro盐值加密_shiro盐值加密并验证

在数据表中存的密码不应该是123456,而应该是123456加密之后的字符串,而且还要求这个加密算法是不可逆的,即由加密后的字符串不能反推回来原来的密码,如果能反推回来那这个加密是没有意义的。著名的加密算法,比如 MD5,SHA1。下面就来介绍如何用shiro进行MD5加密并验证

1.在注册的时候将前端传过来的密码入数据库之前进行加密

public void encryptPassword(User user) {

String salt = new SecureRandomNumberGenerator().nextBytes().toHex();

user.setSalt(salt);

String newPassword = new SimpleHash(

algorithmName,

user.getPassword(),

user.getSalt(),

hashIterations).toHex();

user.setPassword(newPassword);

}

2.在spring容器中自定义realm的配置加入HashedCredentialsMatcher,这样前端输入的密码进入realm就会自动进行加密了,此外还可以配置了加密次数等。

3.这部分就是realm的验证部分了接收前端的参数,取出数据库中的对象,然后根据密码,盐值等进行解密,匹配等等,这部分shiro已经帮我们做好了。

// 认证方法

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

//验证账号密码

UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

User user = userService.findUserByName(token.getUsername());

if(user==null){

throw new UnknownAccountException();

}

if(Boolean.TRUE.equals(user.getLocked())) {

throw new LockedAccountException(); //帐号锁定

}

ByteSource credentialsSalt = ByteSource.Util.bytes(user.getSalt());//这里的参数要给个唯一的;

//最后的比对需要交给安全管理器

//三个参数进行初步的简单认证信息对象的包装

SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(

user.getUsername(), //用户名

user.getPassword(), //密码

credentialsSalt,

getName() //realm name

);

return authenticationInfo;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值