第五章 編碼/加密——《跟我學Shiro》

在涉及到密碼存儲問題上,應該加密/生成密碼摘要存儲,而不是存儲明文密碼。比如之前的600w csdn賬號泄露對用戶可能造成很大損失,因此應加密/生成不可逆的摘要方式存儲。

 

5.1 編碼/解碼 

Shiro提供了base6416進制字符串編碼/解碼的API支持,方便一些編碼解碼操作。Shiro內部的一些數據的存儲/表示都使用了base6416進制字符串。

Java代碼  收藏代碼

  1. String str = "hello";  

  2. String base64Encoded = Base64.encodeToString(str.getBytes());  

  3. String str2 = Base64.decodeToString(base64Encoded);  

  4. Assert.assertEquals(str, str2);   

通過如上方式可以進行base64編碼/解碼操作,更多API請參考其Javadoc

Java代碼  收藏代碼

  1. String str = "hello";  

  2. String base64Encoded = Hex.encodeToString(str.getBytes());  

  3. String str2 = new String(Hex.decode(base64Encoded.getBytes()));  

  4. Assert.assertEquals(str, str2);   

通過如上方式可以進行16進制字符串編碼/解碼操作,更多API請參考其Javadoc

 

還有一個可能經常用到的類CodecSupport,提供了toBytes(str, "utf-8") / toString(bytes, "utf-8")用於在byte數組/String之間轉換。

 

5.2 散列算法

散列算法一般用於生成數據的摘要信息,是一種不可逆的算法,一般適合存儲密碼之類的數據,常見的散列算法如MD5SHA等。一般進行散列時最好提供一個salt(鹽),比如加密密碼“admin”,產生的散列值是“21232f297a57a5a743894a0e4a801fc3”,可以到一些md5解密網站很容易的通過散列值得到密碼“admin”,即如果直接對密碼進行散列相對來說破解更容易,此時我們可以加一些只有系統知道的干擾數據,如用戶名和ID(即鹽);這樣散列的對象是“密碼+用戶名+ID”,這樣生成的散列值相對來說更難破解。

Java代碼  收藏代碼

  1. String str = "hello";  

  2. String salt = "123";  

  3. String md5 = new Md5Hash(str, salt).toString();//還可以轉換爲 toBase64()/toHex()   

如上代碼通過鹽“123MD5散列“hello”。另外散列時還可以指定散列次數,如2次表示:md5(md5(str)):“new Md5Hash(str, salt, 2).toString()”。

  

Java代碼  收藏代碼

  1. String str = "hello";  

  2. String salt = "123";  

  3. String sha1 = new Sha256Hash(str, salt).toString();   

使用SHA256算法生成相應的散列數據,另外還有如SHA1SHA512算法。     

 

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

Java代碼  收藏代碼

  1. String str = "hello";  

  2. String salt = "123";  

  3. //內部使用MessageDigest  

  4. String simpleHash = new SimpleHash("SHA-1", str, salt).toString();   

通過調用SimpleHash時指定散列算法,其內部使用了JavaMessageDigest實現。

 

爲了方便使用,Shiro提供了HashService,默認提供了DefaultHashService實現。

Java代碼  收藏代碼

  1. DefaultHashService hashService = new DefaultHashService(); //默認算法SHA-512  

  2. hashService.setHashAlgorithmName("SHA-512");  

  3. hashService.setPrivateSalt(new SimpleByteSource("123")); //私鹽,默認無  

  4. hashService.setGeneratePublicSalt(true);//是否生成公鹽,默認false  

  5. hashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());//用於生成公鹽。默認就這個  

  6. hashService.setHashIterations(1); //生成Hash值的迭代次數  

  7.   

  8. HashRequest request = new HashRequest.Builder()  

  9.             .setAlgorithmName("MD5").setSource(ByteSource.Util.bytes("hello"))  

  10.             .setSalt(ByteSource.Util.bytes("123")).setIterations(2).build();  

  11. String hex = hashService.computeHash(request).toHex();   

1、首先創建一個DefaultHashService,默認使用SHA-512算法;

2、可以通過hashAlgorithmName屬性修改算法;

3、可以通過privateSalt設置一個私鹽,其在散列時自動與用戶傳入的公鹽混合產生一個新鹽;

4、可以通過generatePublicSalt屬性在用戶沒有傳入公鹽的情況下是否生成公鹽;

5、可以設置randomNumberGenerator用於生成公鹽;

6、可以設置hashIterations屬性來修改默認加密迭代次數;

7、需要構建一個HashRequest,傳入算法、數據、公鹽、迭代次數。

 

SecureRandomNumberGenerator用於生成一個隨機數:

Java代碼  收藏代碼

  1. SecureRandomNumberGenerator randomNumberGenerator =  

  2.      new SecureRandomNumberGenerator();  

  3. randomNumberGenerator.setSeed("123".getBytes());  

  4. String hex = randomNumberGenerator.nextBytes().toHex();   

 

5.3 加密/解密

Shiro還提供對稱式加密/解密算法的支持,如AESBlowfish等;當前還沒有提供對非對稱加密/解密算法支持,未來版本可能提供。

 

AES算法實現:

Java代碼  收藏代碼

  1. AesCipherService aesCipherService = new AesCipherService();  

  2. aesCipherService.setKeySize(128); //設置key長度  

  3. //生成key  

  4. Key key = aesCipherService.generateNewKey();  

  5. String text = "hello";  

  6. //加密  

  7. String encrptText =   

  8. aesCipherService.encrypt(text.getBytes(), key.getEncoded()).toHex();  

  9. //解密  

  10. String text2 =  

  11.  new String(aesCipherService.decrypt(Hex.decode(encrptText), key.getEncoded()).getBytes());  

  12.   

  13. Assert.assertEquals(text, text2);   

更多算法請參考示例com.github.zhangkaitao.shiro.chapter5.hash.CodecAndCryptoTest

 

5.4 PasswordService/CredentialsMatcher

Shiro提供了PasswordServiceCredentialsMatcher用於提供加密密碼及驗證密碼服務。

Java代碼  收藏代碼

  1. public interface PasswordService {  

  2.     //輸入明文密碼得到密文密碼  

  3.     String encryptPassword(Object plaintextPassword) throws IllegalArgumentException;  

  4. }  

Java代碼  收藏代碼

  1. public interface CredentialsMatcher {  

  2.     //匹配用戶輸入的token的憑證(未加密)與系統提供的憑證(已加密)  

  3.     boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);  

  4. }   

Shiro默認提供了PasswordService實現DefaultPasswordServiceCredentialsMatcher實現PasswordMatcherHashedCredentialsMatcher(更強大)。

 

DefaultPasswordService配合PasswordMatcher實現簡單的密碼加密與驗證服務

1、定義Realmcom.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm

Java代碼  收藏代碼

  1. public class MyRealm extends AuthorizingRealm {  

  2.     private PasswordService passwordService;  

  3.     public void setPasswordService(PasswordService passwordService) {  

  4.         this.passwordService = passwordService;  

  5.     }  

  6.      //省略doGetAuthorizationInfo,具體看代碼   

  7.     @Override  

  8.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  

  9.         return new SimpleAuthenticationInfo(  

  10.                 "wu",  

  11.                 passwordService.encryptPassword("123"),  

  12.                 getName());  

  13.     }  

  14. }   

爲了方便,直接注入一個passwordService來加密密碼,實際使用時需要在Service層使用passwordService加密密碼並存到數據庫。

 

2ini配置(shiro-passwordservice.ini

Java代碼  收藏代碼

  1. [main]  

  2. passwordService=org.apache.shiro.authc.credential.DefaultPasswordService  

  3. hashService=org.apache.shiro.crypto.hash.DefaultHashService  

  4. passwordService.hashService=$hashService  

  5. hashFormat=org.apache.shiro.crypto.hash.format.Shiro1CryptFormat  

  6. passwordService.hashFormat=$hashFormat  

  7. hashFormatFactory=org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory  

  8. passwordService.hashFormatFactory=$hashFormatFactory  

  9.   

  10. passwordMatcher=org.apache.shiro.authc.credential.PasswordMatcher  

  11. passwordMatcher.passwordService=$passwordService  

  12.   

  13. myRealm=com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm  

  14. myRealm.passwordService=$passwordService  

  15. myRealm.credentialsMatcher=$passwordMatcher  

  16. securityManager.realms=$myRealm   

2.1passwordService使用DefaultPasswordService,如果有必要也可以自定義;

2.2hashService定義散列密碼使用的HashService,默認使用DefaultHashService(默認SHA-256算法);

2.3hashFormat用於對散列出的值進行格式化,默認使用Shiro1CryptFormat,另外提供了Base64FormatHexFormat,對於有salt的密碼請自定義實現ParsableHashFormat然後把salt格式化到散列值中;

2.4hashFormatFactory用於根據散列值得到散列的密碼和salt;因爲如果使用如SHA算法,那麼會生成一個salt,此salt需要保存到散列後的值中以便之後與傳入的密碼比較時使用;默認使用DefaultHashFormatFactory

2.5passwordMatcher使用PasswordMatcher,其是一個CredentialsMatcher實現;

2.6、將credentialsMatcher賦值給myRealmmyRealm間接繼承了AuthenticatingRealm,其在調用getAuthenticationInfo方法獲取到AuthenticationInfo信息後,會使用credentialsMatcher來驗證憑據是否匹配,如果不匹配將拋出IncorrectCredentialsException異常。

 

3、測試用例請參考com.github.zhangkaitao.shiro.chapter5.hash.PasswordTest

 

另外可以參考配置shiro-jdbc-passwordservice.ini,提供了JdbcRealm的測試用例,測試前請先調用sql/shiro-init-data.sql初始化用戶數據。

 

如上方式的缺點是:salt保存在散列值中;沒有實現如密碼重試次數限制。

 

HashedCredentialsMatcher實現密碼驗證服務

Shiro提供了CredentialsMatcher的散列實現HashedCredentialsMatcher,和之前的PasswordMatcher不同的是,它只用於密碼驗證,且可以提供自己的鹽,而不是隨機生成鹽,且生成密碼散列值的算法需要自己寫,因爲能提供自己的鹽。

 

1、生成密碼散列值

此處我們使用MD5算法,“密碼+鹽(用戶名+隨機數)”的方式生成散列值:

Java代碼  收藏代碼

  1. String algorithmName = "md5";  

  2. String username = "liu";  

  3. String password = "123";  

  4. String salt1 = username;  

  5. String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();  

  6. int hashIterations = 2;  

  7.   

  8. SimpleHash hash = new SimpleHash(algorithmName, password, salt1 + salt2, hashIterations);  

  9. String encodedPassword = hash.toHex();   

如果要寫用戶模塊,需要在新增用戶/重置密碼時使用如上算法保存密碼,將生成的密碼及salt2存入數據庫(因爲我們的散列算法是:md5(md5(密碼+username+salt2)))。

 

2、生成Realmcom.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm2

Java代碼  收藏代碼

  1. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  

  2.     String username = "liu"//用戶名及salt1  

  3.     String password = "202cb962ac59075b964b07152d234b70"//加密後的密碼  

  4.     String salt2 = "202cb962ac59075b964b07152d234b70";  

  5. SimpleAuthenticationInfo ai =   

  6.         new SimpleAuthenticationInfo(username, password, getName());  

  7.     ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); //鹽是用戶名+隨機數  

  8.         return ai;  

  9. }   

此處就是把步驟1中生成的相應數據組裝爲SimpleAuthenticationInfo,通過SimpleAuthenticationInfocredentialsSalt設置鹽,HashedCredentialsMatcher會自動識別這個鹽。

 

如果使用JdbcRealm,需要修改獲取用戶信息(包括鹽)的sql:“select password, password_salt from users where username = ?”,而我們的鹽是由username+password_salt組成,所以需要通過如下ini配置(shiro-jdbc-hashedCredentialsMatcher.ini)修改:

Java代碼  收藏代碼

  1. jdbcRealm.saltStyle=COLUMN  

  2. jdbcRealm.authenticationQuery=select password, concat(username,password_salt) from users where username = ?  

  3. jdbcRealm.credentialsMatcher=$credentialsMatcher   

1saltStyle表示使用密碼+鹽的機制,authenticationQuery第一列是密碼,第二列是鹽;

2、通過authenticationQuery指定密碼及鹽查詢SQL

 

此處還要注意Shiro默認使用了apache commons BeanUtils,默認是不進行Enum類型轉型的,此時需要自己註冊一個Enum轉換器“BeanUtilsBean.getInstance().getConvertUtils().register(new EnumConverter(), JdbcRealm.SaltStyle.class);”具體請參考示例“com.github.zhangkaitao.shiro.chapter5.hash.PasswordTest”中的代碼。

 

另外可以參考配置shiro-jdbc-passwordservice.ini,提供了JdbcRealm的測試用例,測試前請先調用sql/shiro-init-data.sql初始化用戶數據。

 

3ini配置(shiro-hashedCredentialsMatcher.ini

Java代碼  收藏代碼

  1. [main]  

  2. credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher  

  3. credentialsMatcher.hashAlgorithmName=md5  

  4. credentialsMatcher.hashIterations=2  

  5. credentialsMatcher.storedCredentialsHexEncoded=true  

  6. myRealm=com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm2  

  7. myRealm.credentialsMatcher=$credentialsMatcher  

  8. securityManager.realms=$myRealm   

1、通過credentialsMatcher.hashAlgorithmName=md5指定散列算法爲md5,需要和生成密碼時的一樣;

2credentialsMatcher.hashIterations=2,散列迭代次數,需要和生成密碼時的意義;

3credentialsMatcher.storedCredentialsHexEncoded=true表示是否存儲散列後的密碼爲16進制,需要和生成密碼時的一樣,默認是base64

 

此處最需要注意的就是HashedCredentialsMatcher的算法需要和生成密碼時的算法一樣。另外HashedCredentialsMatcher會自動根據AuthenticationInfo的類型是否是SaltedAuthenticationInfo來獲取credentialsSalt鹽。

 

4、測試用例請參考com.github.zhangkaitao.shiro.chapter5.hash.PasswordTest

 

密碼重試次數限制

如在1個小時內密碼最多重試5次,如果嘗試次數超過5次就鎖定1小時,1小時後可再次重試,如果還是重試失敗,可以鎖定如1天,以此類推,防止密碼被暴力破解。我們通過繼承HashedCredentialsMatcher,且使用Ehcache記錄重試次數和超時時間。

 

com.github.zhangkaitao.shiro.chapter5.hash.credentials.RetryLimitHashedCredentialsMatcher

Java代碼  收藏代碼

  1. public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {  

  2.        String username = (String)token.getPrincipal();  

  3.         //retry count + 1  

  4.         Element element = passwordRetryCache.get(username);  

  5.         if(element == null) {  

  6.             element = new Element(username , new AtomicInteger(0));  

  7.             passwordRetryCache.put(element);  

  8.         }  

  9.         AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();  

  10.         if(retryCount.incrementAndGet() > 5) {  

  11.             //if retry count > 5 throw  

  12.             throw new ExcessiveAttemptsException();  

  13.         }  

  14.   

  15.         boolean matches = super.doCredentialsMatch(token, info);  

  16.         if(matches) {  

  17.             //clear retry count  

  18.             passwordRetryCache.remove(username);  

  19.         }  

  20.         return matches;  

  21. }   

如上代碼邏輯比較簡單,即如果密碼輸入正確清除cache中的記錄;否則cache中的重試次數+1,如果超出5次那麼拋出異常表示超出重試次數了。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章