Shiro 编码/加密
在涉及到密碼存儲問題上,應(yīng)該加密 / 生成密碼摘要存儲,而不是存儲明文密碼。比如之前的 600w csdn 賬號泄露對用戶可能造成很大損失,因此應(yīng)加密 / 生成不可逆的摘要方式存儲。
編碼 / 解碼
Shiro 提供了 base64 和 16 進(jìn)制字符串編碼 / 解碼的 API 支持,方便一些編碼解碼操作。Shiro 內(nèi)部的一些數(shù)據(jù)的存儲 / 表示都使用了 base64 和 16 進(jìn)制字符串。
String str = "hello"; String base64Encoded = Base64.encodeToString(str.getBytes()); String str2 = Base64.decodeToString(base64Encoded); Assert.assertEquals(str, str2); 通過如上方式可以進(jìn)行 base64 編碼 / 解碼操作,更多 API 請參考其 Javadoc。
String str = "hello"; String base64Encoded = Hex.encodeToString(str.getBytes()); String str2 = new String(Hex.decode(base64Encoded.getBytes())); Assert.assertEquals(str, str2); 通過如上方式可以進(jìn)行 16 進(jìn)制字符串編碼 / 解碼操作,更多 API 請參考其 Javadoc。
還有一個可能經(jīng)常用到的類 CodecSupport,提供了 toBytes(str,"utf-8") / toString(bytes,"utf-8") 用于在 byte 數(shù)組 /String 之間轉(zhuǎn)換。
散列算法
散列算法一般用于生成數(shù)據(jù)的摘要信息,是一種不可逆的算法,一般適合存儲密碼之類的數(shù)據(jù),常見的散列算法如 MD5、SHA 等。一般進(jìn)行散列時最好提供一個 salt(鹽),比如加密密碼 “admin”,產(chǎn)生的散列值是 “21232f297a57a5a743894a0e4a801fc3”,可以到一些 md5 解密網(wǎng)站很容易的通過散列值得到密碼 “admin”,即如果直接對密碼進(jìn)行散列相對來說破解更容易,此時我們可以加一些只有系統(tǒng)知道的干擾數(shù)據(jù),如用戶名和 ID(即鹽);這樣散列的對象是 “密碼 + 用戶名 +ID”,這樣生成的散列值相對來說更難破解。
String str = "hello"; String salt = "123"; String md5 = new Md5Hash(str, salt).toString();//還可以轉(zhuǎn)換為 toBase64()/toHex() 如上代碼通過鹽 “123”MD5 散列 “hello”。另外散列時還可以指定散列次數(shù),如 2 次表示:md5(md5(str)):“new Md5Hash(str, salt, 2).toString()”。
String str = "hello"; String salt = "123"; String sha1 = new Sha256Hash(str, salt).toString(); 使用 SHA256 算法生成相應(yīng)的散列數(shù)據(jù),另外還有如 SHA1、SHA512 算法。
Shiro 還提供了通用的散列支持:
String str = "hello"; String salt = "123"; //內(nèi)部使用MessageDigest String simpleHash = new SimpleHash("SHA-1", str, salt).toString(); 通過調(diào)用 SimpleHash 時指定散列算法,其內(nèi)部使用了 Java 的 MessageDigest 實(shí)現(xiàn)。
為了方便使用,Shiro 提供了 HashService,默認(rèn)提供了 DefaultHashService 實(shí)現(xiàn)。
DefaultHashService hashService = new DefaultHashService(); //默認(rèn)算法SHA-512 hashService.setHashAlgorithmName("SHA-512"); hashService.setPrivateSalt(new SimpleByteSource("123")); //私鹽,默認(rèn)無 hashService.setGeneratePublicSalt(true);//是否生成公鹽,默認(rèn)false hashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());//用于生成公鹽。默認(rèn)就這個 hashService.setHashIterations(1); //生成Hash值的迭代次數(shù) 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(); SecureRandomNumberGenerator 用于生成一個隨機(jī)數(shù):
SecureRandomNumberGenerator randomNumberGenerator =new SecureRandomNumberGenerator(); randomNumberGenerator.setSeed("123".getBytes()); String hex = randomNumberGenerator.nextBytes().toHex(); 加密 / 解密
Shiro 還提供對稱式加密 / 解密算法的支持,如 AES、Blowfish 等;當(dāng)前還沒有提供對非對稱加密 / 解密算法支持,未來版本可能提供。
AES 算法實(shí)現(xiàn):
AesCipherService aesCipherService = new AesCipherService(); aesCipherService.setKeySize(128); //設(shè)置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。
PasswordService/CredentialsMatcher
Shiro 提供了 PasswordService 及 CredentialsMatcher 用于提供加密密碼及驗(yàn)證密碼服務(wù)。
public interface PasswordService {//輸入明文密碼得到密文密碼String encryptPassword(Object plaintextPassword) throws IllegalArgumentException; } public interface CredentialsMatcher {//匹配用戶輸入的token的憑證(未加密)與系統(tǒng)提供的憑證(已加密)boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info); } Shiro 默認(rèn)提供了 PasswordService 實(shí)現(xiàn) DefaultPasswordService;CredentialsMatcher 實(shí)現(xiàn) PasswordMatcher 及 HashedCredentialsMatcher(更強(qiáng)大)。
DefaultPasswordService 配合 PasswordMatcher 實(shí)現(xiàn)簡單的密碼加密與驗(yàn)證服務(wù)
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,具體看代碼 @Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {return new SimpleAuthenticationInfo("wu", passwordService.encryptPassword("123"),getName());} } 為了方便,直接注入一個 passwordService 來加密密碼,實(shí)際使用時需要在 Service 層使用 passwordService 加密密碼并存到數(shù)據(jù)庫。
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 - passwordService 使用 DefaultPasswordService,如果有必要也可以自定義;
- hashService 定義散列密碼使用的 HashService,默認(rèn)使用 DefaultHashService(默認(rèn) SHA-256 算法);
- hashFormat 用于對散列出的值進(jìn)行格式化,默認(rèn)使用 Shiro1CryptFormat,另外提供了 Base64Format 和 HexFormat,對于有 salt 的密碼請自定義實(shí)現(xiàn) ParsableHashFormat 然后把 salt 格式化到散列值中;
- hashFormatFactory 用于根據(jù)散列值得到散列的密碼和 salt;因?yàn)槿绻褂萌?SHA 算法,那么會生成一個 salt,此 salt 需要保存到散列后的值中以便之后與傳入的密碼比較時使用;默認(rèn)使用 DefaultHashFormatFactory;
- passwordMatcher 使用 PasswordMatcher,其是一個 CredentialsMatcher 實(shí)現(xiàn);
- 將 credentialsMatcher 賦值給 myRealm,myRealm 間接繼承了 AuthenticatingRealm,其在調(diào)用 getAuthenticationInfo 方法獲取到 AuthenticationInfo 信息后,會使用 credentialsMatcher 來驗(yàn)證憑據(jù)是否匹配,如果不匹配將拋出 IncorrectCredentialsException 異常。
3、測試用例請參考 com.github.zhangkaitao.shiro.chapter5.hash.PasswordTest。
另外可以參考配置 shiro-jdbc-passwordservice.ini,提供了 JdbcRealm 的測試用例,測試前請先調(diào)用 sql/shiro-init-data.sql 初始化用戶數(shù)據(jù)。
如上方式的缺點(diǎn)是:salt 保存在散列值中;沒有實(shí)現(xiàn)如密碼重試次數(shù)限制。
HashedCredentialsMatcher 實(shí)現(xiàn)密碼驗(yàn)證服務(wù)
Shiro 提供了 CredentialsMatcher 的散列實(shí)現(xiàn) HashedCredentialsMatcher,和之前的 PasswordMatcher 不同的是,它只用于密碼驗(yàn)證,且可以提供自己的鹽,而不是隨機(jī)生成鹽,且生成密碼散列值的算法需要自己寫,因?yàn)槟芴峁┳约旱柠}。
1、生成密碼散列值
此處我們使用 MD5 算法,“密碼 + 鹽(用戶名 + 隨機(jī)數(shù))” 的方式生成散列值:
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 存入數(shù)據(jù)庫(因?yàn)槲覀兊纳⒘兴惴ㄊ?#xff1a;md5(md5(密碼 +username+salt2)))。
2、生成 Realm(com.github.zhangkaitao.shiro.chapter5.hash.realm.MyRealm2)
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {String username = "liu"; //用戶名及salt1String password = "202cb962ac59075b964b07152d234b70"; //加密后的密碼String salt2 = "202cb962ac59075b964b07152d234b70"; SimpleAuthenticationInfo ai = new SimpleAuthenticationInfo(username, password, getName());ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); //鹽是用戶名+隨機(jī)數(shù)return ai; } 此處就是把步驟 1 中生成的相應(yīng)數(shù)據(jù)組裝為 SimpleAuthenticationInfo,通過 SimpleAuthenticationInfo 的 credentialsSalt 設(shè)置鹽,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 - saltStyle 表示使用密碼 + 鹽的機(jī)制,authenticationQuery 第一列是密碼,第二列是鹽;
- 通過 authenticationQuery 指定密碼及鹽查詢 SQL;
此處還要注意 Shiro 默認(rèn)使用了 apache commons BeanUtils,默認(rèn)是不進(jìn)行 Enum 類型轉(zhuǎn)型的,此時需要自己注冊一個 Enum 轉(zhuǎn)換器 “BeanUtilsBean.getInstance().getConvertUtils().register(new EnumConverter(), JdbcRealm.SaltStyle.class);” 具體請參考示例 “com.github.zhangkaitao.shiro.chapter5.hash.PasswordTest” 中的代碼。
另外可以參考配置 shiro-jdbc-passwordservice.ini,提供了 JdbcRealm 的測試用例,測試前請先調(diào)用 sql/shiro-init-data.sql 初始化用戶數(shù)據(jù)。
3、ini 配置(shiro-hashedCredentialsMatcher.ini)
[main] 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 securityManager.realms=$myRealm - 通過 credentialsMatcher.hashAlgorithmName=md5 指定散列算法為 md5,需要和生成密碼時的一樣;
- credentialsMatcher.hashIterations=2,散列迭代次數(shù),需要和生成密碼時的意義;
- credentialsMatcher.storedCredentialsHexEncoded=true 表示是否存儲散列后的密碼為 16 進(jìn)制,需要和生成密碼時的一樣,默認(rèn)是 base64;
此處最需要注意的就是 HashedCredentialsMatcher 的算法需要和生成密碼時的算法一樣。另外 HashedCredentialsMatcher 會自動根據(jù) AuthenticationInfo 的類型是否是 SaltedAuthenticationInfo 來獲取 credentialsSalt 鹽。
4、測試用例請參考 com.github.zhangkaitao.shiro.chapter5.hash.PasswordTest。
密碼重試次數(shù)限制
如在 1 個小時內(nèi)密碼最多重試 5 次,如果嘗試次數(shù)超過 5 次就鎖定 1 小時,1 小時后可再次重試,如果還是重試失敗,可以鎖定如 1 天,以此類推,防止密碼被暴力破解。我們通過繼承 HashedCredentialsMatcher,且使用 Ehcache 記錄重試次數(shù)和超時時間。
com.github.zhangkaitao.shiro.chapter5.hash.credentials.RetryLimitHashedCredentialsMatcher:
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {String username = (String)token.getPrincipal();//retry count + 1Element 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 throwthrow new ExcessiveAttemptsException();}boolean matches = super.doCredentialsMatch(token, info);if(matches) {//clear retry countpasswordRetryCache.remove(username);}return matches; } 如上代碼邏輯比較簡單,即如果密碼輸入正確清除 cache 中的記錄;否則 cache 中的重試次數(shù) +1,如果超出 5 次那么拋出異常表示超出重試次數(shù)了。
轉(zhuǎn)載于:https://www.cnblogs.com/fly1027/p/8622827.html
總結(jié)
以上是生活随笔為你收集整理的Shiro 编码/加密的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据库拆分案例
- 下一篇: android入门--环境搭建