在数据表中存的密码不应该是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;
}