您的位置:首页 > 其它

shiro salt

2016-05-23 07:49 351 查看

1.1 散列算法

散列算法一般用于生成一段文本的摘要信息,散列算法不可逆,将内容可以生成摘要,无法将摘要转成原始内容。散列算法常用于对密码进行散列,常用的散列算法有MD5、SHA。分享牛系列,分享牛专栏,分享牛
一般散列算法需要提供一个salt(盐)与原始内容生成摘要信息,这样做的目的是为了安全性,比如:111111的md5值是:96e79218965eb72c92a549dd5a330112,拿着“96e79218965eb72c92a549dd5a330112”去md5破解网站很容易进行破解,如果要是对111111和salt(盐,一个随机数)进行散列,这样虽然密码都是111111加不同的盐会生成不同的散列值。分享牛系列,分享牛专栏,分享牛

1.1.1 例子

//md5加密,不加盐
String password_md5 = new Md5Hash("111111").toString();
System.out.println("md5加密,不加盐="+password_md5);

//md5加密,加盐,一次散列
String password_md5_sale_1 = new Md5Hash("111111", "eteokues", 1).toString();
System.out.println("password_md5_sale_1="+password_md5_sale_1);
String password_md5_sale_2 = new Md5Hash("111111", "uiwueylm", 1).toString();
System.out.println("password_md5_sale_2="+password_md5_sale_2);
//两次散列相当于md5(md5())

//使用SimpleHash
String simpleHash = new SimpleHash("MD5", "111111", "eteokues",1).toString();
System.out.println(simpleHash);

1.1.2 在realm中使用

实际应用是将盐和散列后的值存在数据库中,自动realm从数据库取出盐和加密后的值由shiro完成密码校验。

1.1.2.1 自定义realm

@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {

//用户账号
String username = (String) token.getPrincipal();
//根据用户账号从数据库取出盐和加密后的值
//..这里使用静态数据
//如果根据账号没有找到用户信息则返回null,shiro抛出异常“账号不存在”

//按照固定规则加密码结果 ,此密码 要在数据库存储,原始密码 是111111,盐是eteokues
String password = "cb571f7bd7a6f73ab004a70322b963d5";
//盐,随机数,此随机数也在数据库存储
String salt = "eteokues";

//返回认证信息
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
username, password, ByteSource.Util.bytes(salt),getName());

return simpleAuthenticationInfo;
}

1.1.2.2 realm配置

配置shiro-cryptography.ini
[main]#定义凭证匹配器credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher#散列算法credentialsMatcher.hashAlgorithmName=md5#散列次数credentialsMatcher.hashIterations=1 #将凭证匹配器设置到realmcustomRealm=cn.shareniu.shiro.authentication.realm.CustomRealm2customRealm.credentialsMatcher=$credentialsMatchersecurityManager.realms=$customRealm

1.1.2.3 测试代码

测试代码同上个章节,注意修改ini路径。
分享牛原创(尊重原创 转载对的时候第一行请注明,转载出处来自分享牛http://blog.csdn.net/qq_30739519) Java架构师交流群 523988350
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: