springboot+shiro实现自定义密码加密及验证
前言
本篇文章不展示如何集成springboot和shiro,仅展示自定义密码加密方式的相关部门,如何集成请查看其它相关文章
正文
因shiro没有集成Bcrypt加密方式,需要自己去继承实现相关方法。
1.创建一个类,继承 SimpleCredentialsMatcher
类
此类用于重写验证密码方法,验证完成后返回true false来告诉shiro密码是否正确。
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
//获得前台传过来的密码
String originalPassword=(String)token.getCredentials();
//这是数据库里查出来的密码
String sqlOriginalPassword=(String)info.getCredentials();
//进行比对,BcryptUtil工具类会在文章末尾放出
return BcryptUtil.match(originalPassword,sqlOriginalPassword);
}
}
2.修改 身份认证Realm
将上面重写的类注入到Realm中
3.修改你继承 AuthorizingRealm
类中的 doGetAuthenticationInfo
方法
因shiro自带加密中salt都需要单独放一个字段,Bcrypt的salt是包含在password里面的,所以
返回的信息中不需要带salt(你要愿意也可以放进去,反正用不到)。
4. 工具类中 BCrypt
类获得方式
**注意:**工具类中 BCrypt
类 可以通过引入两种依赖获得。
1.直接引入
<dependency>
<groupId>de.svenkubiak</groupId>
<artifactId>jBCrypt</artifactId>
<version>0.4.1</version>
</dependency>
2.引入 hutool
工具包 ( 推荐 )
理由:hutool 中集成了非常多的工具类,可以省下去网上一个个翻工具类并且Ctrl+C的时间
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.8</version>
</dependency>
5.BcryptUtil
工具类
public class BcryptUtil {
public static String encode(String password){
return BCrypt.hashpw(password, BCrypt.gensalt()); //对明文密码进行加密,并返回加密后的密码
}
public static boolean match(String password, String encodePassword){ //将明文密码跟加密后的密码进行匹配,如果一致返回true,否则返回false
return BCrypt.checkpw(password,encodePassword);
}
// public static void main(String[] args){
// String password = "123456"; //明文密码
// String psd = BcryptUtil.encode(password); //加密后的密码
// System.out.println(BcryptUtil.match(password, psd)); //如果一致,返回true,否则返回false
// }
}
以上为具体示例,如果有问题可加qq讨论:1016400304