散列算法概述
散列算法一般用于生成数据的摘要信息,是一种不可逆的算法,一般适合存储密码之类的数据,常见的散列算法如MD5、SHA等。一般进行散列时最好提供一个salt(盐)
比如 加密密码“admin”,产生的散列值是“21232f297a57a5a743894a0e4a801fc3”,可以到一 些md5 解密网站很容易的通过散列值得到密码“admin”,即如果直接对密码进行散列相对来说破解更容易
此时我们可以加一些只有系统知道的干扰数据,如用户名和ID(即盐),这样散列的对象是“密码+用户名+ID”,这样生成的散列值相对来说更难破解。
代码实现
加密算法
public void test03() {
String username = "tom";
String password = "1111";
// 第一个参数:加密字符串, 第二个参数:盐(干扰信息), 第三个个参数:散列次数(加密次数)
String s1 = new Md5Hash(password, username).toBase64();
System.out.println(s1);
String s2 = new Md5Hash(password, username).toHex();
System.out.println(s2);
String s3 = new Md5Hash(password, username, 2).toString();
System.out.println(s3);
// 使用通用的Hash加密的工具类SimpleHash实现加密
String s4 = new SimpleHash("md5", password, username, 3).toString();
// String s2 = new SimpleHash("sha1", password, username, 3).toBase64();
// String s3 = new SimpleHash("sha-256", password, username, 3).toBase64();
System.out.println(s4);
}
Realm实现加密认证
public class UserRealm extends AuthorizingRealm {
@Override
public String getName() {
return "UserRealm";
}
//用于认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//从token中获取身份信息
String username = (String)token.getPrincipal();
//根据用户名到数据库中取出用户信息 如果查询不到 返回null
//按照固定规则加密码结果 ,此密码 要在数据库存储,原始密码 是1111,盐是laolei 2次散列
String password = "1620d20433da92e2523928e351e90f97";//假如从数据库中获取密码为1111
//返回认证信息 (将username作为盐)
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(username),this.getName());
return simpleAuthenticationInfo;
}
//用于授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
}
shiro.ini
#定义凭证匹配器
credentialsMatcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法
credentialsMatcher.hashAlgorithmName = md5
#散列次数
credentialsMatcher.hashIterations = 2
#将凭证匹配器设置到realm
userRealm=com.tuojun.realm.UserRealm
userRealm.credentialsMatcher = $credentialsMatcher
securityManager.realms = $userRealm