shiro md5加密
shrio 提供了一些字符串加密的api
Object result = new SimpleHash("md5", "1234", ByteSource.Util.bytes("ckh"), 10);
System.out.println(result);
SimpleHash simpleHash = new SimpleHash("md5","1234",null,1);
System.out.println(simpleHash);
Md5Hash md5Hash = new Md5Hash("1234");
System.out.println(md5Hash.toString());
在shiro中的认证中添加md5加密的方法
package cn.ckh2019.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
/**
* @author Chen Kaihong
* 2019-06-09 21:48
*/
public class UserRealm extends AuthorizingRealm {
@Override
public String getName() {
return "userRealm";
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
/**
* 完成身份认证(从数据库中取数据)
* 返回认证信息,如果认证失败返回null
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//获取用户输入的用户名
String username = (String) token.getPrincipal();
//根据用户名到数据库查询密码信息
//假定从数据库获取的密码是1234经过md5加密后的字符串
String password = "6fbf9e1b65c1bef784eafff34b93b482";
//假定从数据库获取的盐值是 "ckh"
String salt = "ckh";
//将从数据库查询的信息封装到SimpleAuthenticationInfo中
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,password,ByteSource.Util.bytes(salt),getName());
return info;
}
}
下面是shiro.ini
[main]
credentialsMatcher= org.apache.shiro.authc.credential.HashedCredentialsMatcher
credentialsMatcher.hashAlgorithmName=md5
credentialsMatcher.hashIterations=10
userRealm=cn.ckh2019.realm.UserRealm
userRealm.credentialsMatcher=$credentialsMatcher
securityManager.realm=$userRealm
测试代码
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("张三","1234");
//6.进行用户验证
try {
subject.login(token);
//7.通过subject来判断用户是否通过验证
if (subject.isAuthenticated()) {
System.out.println("登录成功");
}
}catch(IncorrectCredentialsException e) {
System.out.println("密码错误");
}catch(UnknownAccountException e){
System.out.println("用户名错误");
}