《跟我学Shiro》学习笔记 第四章:编码/加密

前言

密码存储应该采用加密/生产密码摘要存储。而不是采用明文存储,这期我们就来学习一下Shiro在编码与加密方面的功能。

4.1编码/解码

Shiro提供了base64和16进制字符串编码/解码的API支持,方便一些编码解码操作。Shiro内部的一些数据的存储/表示都使用了base64和16进制字符串。

@Test
public void base64encode(){
    String str = "hello";
    String base64Encoded = Base64.encodeToString(str.getBytes());

    log.info("编码后:"+base64Encoded);

    String str2 = Base64.decodeToString(base64Encoded);

    log.info("解码后:"+str2);
}

通过如上方式可以进行base64编码/解码操作。

@Test
public void hexEncode(){
    String str = "hello";
    String base64Encoded = Hex.encodeToString(str.getBytes());
    log.info("编码后:"+base64Encoded);
    String str2 = new String(Hex.decode(base64Encoded.getBytes()));
    log.info("解码后:"+str2);
}

通过如上方式可以进行16进制字符串编码/解码操作。

4.2散列算法

散列算法一般用于生成数据的摘要信息,是一种不可逆的算法,一般适合存储密码之类的数据,常见的散列算法如MD5、SHA等。一般进行散列时最好提供一个salt(盐),比如加密密码“admin”,产生的散列值是“21232f297a57a5a743894a0e4a801fc3”,可以到一些md5解密网站很容易的通过散列值得到密码“admin”,即如果直接对密码进行散列相对来说破解更容易,此时我们可以加一些只有系统知道的干扰数据,如用户名和ID(即盐);这样散列的对象是“密码+用户名+ID”,这样生成的散列值相对来说更难破解。

@Test
public void md5(){
    String str = "hello";
    String salt = "123";
    String md5 = new Md5Hash(str,salt).toString();
    log.info(md5);
}

md5算法散列。

@Test
public void sha256(){
    String str = "hello";
    String salt = "123";
    String sha256 = new Sha256Hash(str,salt).toString();
    log.info(sha256);
}

sha256散列算法。

Shiro还提供了通用的散列支持:

@Test
public void messageDigest(){
    String str = "hello";
    String salt = "123";
    //内部使用MessageDigest
    String simpleHash = new SimpleHash("SHA-1", str, salt).toString();
    log.info(simpleHash);
}

通过调用SimpleHash时指定散列算法,其内部使用了Java的MessageDigest实现。

为了方便使用,Shiro提供了HashService,默认提供了DefaultHashService实现。

@Test
public void testHashService() {
    //默认算法SHA-512
    DefaultHashService hashService = new DefaultHashService();
    hashService.setHashAlgorithmName("SHA-512");
    //私盐,默认无
    hashService.setPrivateSalt(new SimpleByteSource("123"));
    //是否生成公盐,默认false
    hashService.setGeneratePublicSalt(true);
    //用于生成公盐。默认就这个
    hashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());
    //生成Hash值的迭代次数
    hashService.setHashIterations(1);

    HashRequest request = new HashRequest.Builder()
    .setAlgorithmName("MD5").setSource(ByteSource.Util.bytes("hello"))
    .setSalt(ByteSource.Util.bytes("123")).setIterations(2).build();
    String hex = hashService.computeHash(request).toHex();
    log.info(hex);
}
  1. 首先创建一个DefaultHashService,默认使用SHA-512算法;
  2. 可以通过hashAlgorithmName属性修改算法;
  3. 可以通过privateSalt设置一个私盐,其在散列时自动与用户传入的公盐混合产生一个新盐;
  4. 可以通过generatePublicSalt属性在用户没有传入公盐的情况下是否生成公盐;
  5. 可以设置randomNumberGenerator用于生成公盐;
  6. 可以设置hashIterations属性来修改默认加密迭代次数;
  7. 需要构建一个HashRequest,传入算法、数据、公盐、迭代次数。

4.3加密/解密

Shiro还提供对称式加密/解密算法的支持,如AES、Blowfish等;当前还没有提供对非对称加密/解密算法支持,未来版本可能提供。

AES算法实现:

@Test
public void aes() {
    AesCipherService aesCipherService = new AesCipherService();
    //设置key长度
    aesCipherService.setKeySize(128);
    //生成key
    Key key = aesCipherService.generateNewKey();
    String text = "hello";
    //加密
    String encrptText = aesCipherService.encrypt(text.getBytes(), key.getEncoded()).toHex();
    log.info(encrptText);
    //解密  
    String text2 = new String(aesCipherService.decrypt(Hex.decode(encrptText), key.getEncoded()).getBytes());

    log.info(text2);
}

4.4PasswordService/CredentialsMatcher

Shiro提供了PasswordService及CredentialsMatcher用于提供加密密码及验证密码服务。

public interface PasswordService {  
    //输入明文密码得到密文密码  
    String encryptPassword(Object plaintextPassword) throws IllegalArgumentException;  
}  
public interface CredentialsMatcher {  
    //匹配用户输入的token的凭证(未加密)与系统提供的凭证(已加密)  
    boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);  
}   

Shiro默认提供了PasswordService实现DefaultPasswordService;CredentialsMatcher实现PasswordMatcher及HashedCredentialsMatcher(更强大)。

DefaultPasswordService配合PasswordMatcher实现简单的密码加密与验证服务

  1. 定义Realm

    public class MyRealm extends AuthorizingRealm {
    
        private PasswordService passwordService;
    
        public void setPasswordService(PasswordService passwordService){
            this.passwordService = passwordService;
        }
    
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            return null;
        }
    
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            return new SimpleAuthenticationInfo("zhang",passwordService.encryptPassword("123"),getName());
        }
    }
    

    为了方便,直接注入一个passwordService来加密密码,实际使用时需要在Service层使用passwordService加密密码并存到数据库。

  2. ini配置(shiro-passwordservice.ini)

    [main]
    passwordService=org.apache.shiro.authc.credential.DefaultPasswordService
    hashService=org.apache.shiro.crypto.hash.DefaultHashService
    passwordService.hashService=$hashService
    hashFormat=org.apache.shiro.crypto.hash.format.Shiro1CryptFormat
    passwordService.hashFormat=$hashFormat
    hashFormatFactory=org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory
    passwordService.hashFormatFactory=$hashFormatFactory
    
    passwordMatcher=org.apache.shiro.authc.credential.PasswordMatcher
    passwordMatcher.passwordService=$passwordService
    
    myRealm=com.zhaojun.shiro.chapter4.realm.MyRealm
    myRealm.passwordService=$passwordService
    myRealm.credentialsMatcher=$passwordMatcher
    securityManager.realms=$myRealm
    
    • passwordService使用DefaultPasswordService,如果有必要也可以自定义;
    • hashService定义散列密码使用的HashService,默认使用DefaultHashService(默认SHA-256算法);
    • hashFormat用于对散列出的值进行格式化,默认使用Shiro1CryptFormat,另外提供了Base64Format和HexFormat,对于有salt的密码请自定义实现ParsableHashFormat然后把salt格式化到散列值中;
    • hashFormatFactory用于根据散列值得到散列的密码和salt;因为如果使用如SHA算法,那么会生成一个salt,此salt需要保存到散列后的值中以便之后与传入的密码比较时使用;默认使用DefaultHashFormatFactory;
    • passwordMatcher使用PasswordMatcher,其是一个CredentialsMatcher实现;
    • 将credentialsMatcher赋值给myRealm,myRealm间接继承了AuthenticatingRealm,其在调用getAuthenticationInfo方法获取到AuthenticationInfo信息后,会使用credentialsMatcher来验证凭据是否匹配,如果不匹配将抛出IncorrectCredentialsException异常。

    HashedCredentialsMatcher实现密码验证服务

    Shiro提供了CredentialsMatcher的散列实现HashedCredentialsMatcher,和之前的PasswordMatcher不同的是,它只用于密码验证,且可以提供自己的盐,而不是随机生成盐,且生成密码散列值的算法需要自己写,因为能提供自己的盐。

    1. 生成密码散列值

      此处我们使用MD5算法,“密码+盐(用户名+随机数)”的方式生成散列值:

      String algorithmName = "md5";  
      String username = "liu";  
      String password = "123";  
      String salt1 = username;  
      String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();  
      int hashIterations = 2;  
        
      SimpleHash hash = new SimpleHash(algorithmName, password, salt1 + salt2, hashIterations);  
      String encodedPassword = hash.toHex();   
      

    如果要写用户模块,需要在新增用户/重置密码时使用如上算法保存密码,将生成的密码及salt2存入数据库(因为我们的散列算法是:md5(md5(密码+username+salt2)))。

    1. 生成Realm

      @Override
          protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
              //用户名及salt1
              String username = "liu";
              //加密后的密码
              String password = "202cb962ac59075b964b07152d234b70";
              String salt2 = "202cb962ac59075b964b07152d234b70";
              //盐是用户名+随机数
              SimpleAuthenticationInfo ai =
                      new SimpleAuthenticationInfo(username, password, getName());
              ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2));
              return ai;
          }
      

      如果使用JdbcRealm,需要修改获取用户信息(包括盐)的sql:“select password, password_salt from users where username = ?”,而我们的盐是由username+password_salt组成,所以需要通过如下ini配置修改:

      jdbcRealm.saltStyle=COLUMN  
      jdbcRealm.authenticationQuery=select password, concat(username,password_salt) from users where username = ?  
      jdbcRealm.credentialsMatcher=$credentialsMatcher 
      

      1、saltStyle表示使用密码+盐的机制,authenticationQuery第一列是密码,第二列是盐;

      2、通过authenticationQuery指定密码及盐查询SQL;


张开涛的博客:http://jinnianshilongnian.iteye.com/category/305053

我的博客:https://zhaojun0193.github.io

本文代码地址:https://github.com/zhaojun0193/shiro-example

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容