天天看點

跟開濤老師學shiro -- 編碼/加密

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

Shiro提供了base64和16進制字元串編碼/解碼的API支援,友善一些編碼解碼操作。Shiro内部的一些資料的存儲/表示都使用了base64和16進制字元串。

Java代碼  

String str = "hello";  

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

String str2 = Base64.decodeToString(base64Encoded);  

Assert.assertEquals(str, str2);   

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

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

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

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

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

String salt = "123";  

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

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

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

使用SHA256算法生成相應的散列資料,另外還有如SHA1、SHA512算法。     

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

//内部使用MessageDigest  

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

為了友善使用,Shiro提供了HashService,預設提供了DefaultHashService實作。

DefaultHashService hashService = new DefaultHashService(); //預設算法SHA-512  

hashService.setHashAlgorithmName("SHA-512");  

hashService.setPrivateSalt(new SimpleByteSource("123")); //私鹽,預設無  

hashService.setGeneratePublicSalt(true);//是否生成公鹽,預設false  

hashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());//用于生成公鹽。預設就這個  

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

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();   

1、首先建立一個DefaultHashService,預設使用SHA-512算法;

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

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

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

5、可以設定randomNumberGenerator用于生成公鹽;

6、可以設定hashIterations屬性來修改預設加密疊代次數;

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

SecureRandomNumberGenerator用于生成一個随機數:

SecureRandomNumberGenerator randomNumberGenerator =  

     new SecureRandomNumberGenerator();  

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

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

Shiro還提供對稱式加密/解密算法的支援,如AES、Blowfish等;目前還沒有提供對非對稱加密/解密算法支援,未來版本可能提供。

AES算法實作:

AesCipherService aesCipherService = new AesCipherService();  

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

//生成key  

Key key = aesCipherService.generateNewKey();  

String text = "hello";  

//加密  

String encrptText =   

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

//解密  

String text2 =  

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

Assert.assertEquals(text, text2);   

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

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(com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm)

public class MyRealm extends AuthorizingRealm {  

    private PasswordService passwordService;  

    public void setPasswordService(PasswordService passwordService) {  

        this.passwordService = passwordService;  

    }  

     //省略doGetAuthorizationInfo,具體看代碼   

    @Override  

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  

        return new SimpleAuthenticationInfo(  

                "wu",  

                passwordService.encryptPassword("123"),  

                getName());  

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.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm  

myRealm.passwordService=$passwordService  

myRealm.credentialsMatcher=$passwordMatcher  

securityManager.realms=$myRealm   

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

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

2.3、hashFormat用于對散列出的值進行格式化,預設使用Shiro1CryptFormat,另外提供了Base64Format和HexFormat,對于有salt的密碼請自定義實作ParsableHashFormat然後把salt格式化到散列值中;

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

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

2.6、将credentialsMatcher指派給myRealm,myRealm間接繼承了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算法,“密碼+鹽(使用者名+随機數)”的方式生成散列值:

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)))。

2、生成Realm(com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm2)

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  

    String username = "liu"; //使用者名及salt1  

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

    String salt2 = "202cb962ac59075b964b07152d234b70";  

SimpleAuthenticationInfo ai =   

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

    ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); //鹽是使用者名+随機數  

        return ai;  

此處就是把步驟1中生成的相應資料組裝為SimpleAuthenticationInfo,通過SimpleAuthenticationInfo的credentialsSalt設定鹽,HashedCredentialsMatcher會自動識别這個鹽。

如果使用JdbcRealm,需要修改擷取使用者資訊(包括鹽)的sql:“select password, password_salt from users where username = ?”,而我們的鹽是由username+password_salt組成,是以需要通過如下ini配置(shiro-jdbc-hashedCredentialsMatcher.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;

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

3、ini配置(shiro-hashedCredentialsMatcher.ini)

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

credentialsMatcher.hashAlgorithmName=md5  

credentialsMatcher.hashIterations=2  

credentialsMatcher.storedCredentialsHexEncoded=true  

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

myRealm.credentialsMatcher=$credentialsMatcher  

1、通過credentialsMatcher.hashAlgorithmName=md5指定雜湊演算法為md5,需要和生成密碼時的一樣;

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

3、credentialsMatcher.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記錄重試次數和逾時時間。

----   筆記分割線start ----

跟開濤老師學shiro -- 編碼/加密
shiro本身和ehcache有實作,不要再找其他ehcache的實作了。 看看ehcache被哪些項目用過:
跟開濤老師學shiro -- 編碼/加密

----   筆記分割線end ---- 

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

public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {  

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

        //retry count + 1  

        Element element = passwordRetryCache.get(username);  

        if(element == null) {  

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

            passwordRetryCache.put(element);  

        }  

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

        if(retryCount.incrementAndGet() > 5) {  

            //if retry count > 5 throw  

            throw new ExcessiveAttemptsException();  

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

        if(matches) {  

            //clear retry count  

            passwordRetryCache.remove(username);  

        return matches;  

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

 本文轉自二郎三郎部落格園部落格,原文連結:http://www.cnblogs.com/haore147/p/5482017.html,如需轉載請自行聯系原作者