欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

shiro編碼和加密代碼詳解

 更新時(shí)間:2017年09月20日 09:27:39   作者:動(dòng)力節(jié)點(diǎn)  
Shiro提供了base64和16進(jìn)制字符串編碼/解碼的API支持,方便一些編碼解碼操作。下面通過實(shí)例代碼給大家詳解shiro編碼和加密知識,感興趣的朋友一起看看吧

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

編碼/解碼 

Shiro提供了base64和16進(jìn)制字符串編碼/解碼的API支持,方便一些編碼解碼操作。Shiro內(nèi)部的一些數(shù)據(jù)的存儲/表示都使用了base64和16進(jìn)制字符串。

Java代碼  

String str = "hello"; 
String base64Encoded = Base64.encodeToString(str.getBytes()); 
String str2 = Base64.decodeToString(base64Encoded); 
Assert.assertEquals(str, str2);  

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

Java代碼  

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。 

還有一個(gè)可能經(jīng)常用到的類CodecSupport,提供了toBytes(str, "utf-8") / toString(bytes, "utf-8")用于在byte數(shù)組/String之間轉(zhuǎn)換。 

散列算法

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

Java代碼  

String str = "hello"; 
String salt = "123"; 
String md5 = new Md5Hash(str, salt).toString();//還可以轉(zhuǎn)換為 toBase64()/toHex()  

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

Java代碼  

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

使用SHA256算法生成相應(yīng)的散列數(shù)據(jù),另外還有如SHA1、SHA512算法。      

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

Java代碼  

String str = "hello"; 
String salt = "123"; 
//內(nèi)部使用MessageDigest 
String simpleHash = new SimpleHash("SHA-1", str, salt).toString();  

通過調(diào)用SimpleHash時(shí)指定散列算法,其內(nèi)部使用了Java的MessageDigest實(shí)現(xiàn)。 

為了方便使用,Shiro提供了HashService,默認(rèn)提供了DefaultHashService實(shí)現(xiàn)。

Java代碼  

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)就這個(gè) 
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();  

1、首先創(chuàng)建一個(gè)DefaultHashService,默認(rèn)使用SHA-512算法;

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

3、可以通過privateSalt設(shè)置一個(gè)私鹽,其在散列時(shí)自動(dòng)與用戶傳入的公鹽混合產(chǎn)生一個(gè)新鹽;

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

5、可以設(shè)置randomNumberGenerator用于生成公鹽;

6、可以設(shè)置hashIterations屬性來修改默認(rèn)加密迭代次數(shù);

7、需要構(gòu)建一個(gè)HashRequest,傳入算法、數(shù)據(jù)、公鹽、迭代次數(shù)。 

SecureRandomNumberGenerator用于生成一個(gè)隨機(jī)數(shù):

Java代碼  

SecureRandomNumberGenerator randomNumberGenerator = 
   new SecureRandomNumberGenerator(); 
randomNumberGenerator.setSeed("123".getBytes()); 
String hex = randomNumberGenerator.nextBytes().toHex();  

加密/解密

Shiro還提供對稱式加密/解密算法的支持,如AES、Blowfish等;當(dāng)前還沒有提供對非對稱加密/解密算法支持,未來版本可能提供。 

AES算法實(shí)現(xiàn):

Java代碼  

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

Java代碼  

public interface PasswordService { 
  //輸入明文密碼得到密文密碼 
  String encryptPassword(Object plaintextPassword) throws IllegalArgumentException; 
} 

Java代碼 

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)

Java代碼  

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

為了方便,直接注入一個(gè)passwordService來加密密碼,實(shí)際使用時(shí)需要在Service層使用passwordService加密密碼并存到數(shù)據(jù)庫。 

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

Java代碼  

[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,默認(rèn)使用DefaultHashService(默認(rèn)SHA-256算法);

2.3、hashFormat用于對散列出的值進(jìn)行格式化,默認(rèn)使用Shiro1CryptFormat,另外提供了Base64Format和HexFormat,對于有salt的密碼請自定義實(shí)現(xiàn)ParsableHashFormat然后把salt格式化到散列值中;

2.4、hashFormatFactory用于根據(jù)散列值得到散列的密碼和salt;因?yàn)槿绻褂萌鏢HA算法,那么會生成一個(gè)salt,此salt需要保存到散列后的值中以便之后與傳入的密碼比較時(shí)使用;默認(rèn)使用DefaultHashFormatFactory;

2.5、passwordMatcher使用PasswordMatcher,其是一個(gè)CredentialsMatcher實(shí)現(xiàn);

2.6、將credentialsMatcher賦值給myRealm,myRealm間接繼承了AuthenticatingRealm,其在調(diào)用getAuthenticationInfo方法獲取到AuthenticationInfo信息后,會使用credentialsMatcher來驗(yàn)證憑據(jù)是否匹配,如果不匹配將拋出IncorrectCredentialsException異常。 

另外可以參考配置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ù))”的方式生成散列值:

Java代碼  

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

如果要寫用戶模塊,需要在新增用戶/重置密碼時(shí)使用如上算法保存密碼,將生成的密碼及salt2存入數(shù)據(jù)庫(因?yàn)槲覀兊纳⒘兴惴ㄊ牵簃d5(md5(密碼+username+salt2)))。 

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

Java代碼  

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)); //鹽是用戶名+隨機(jī)數(shù) 
    return ai; 
} 
 

此處就是把步驟1中生成的相應(yīng)數(shù)據(jù)組裝為SimpleAuthenticationInfo,通過SimpleAuthenticationInfo的credentialsSalt設(shè)置鹽,HashedCredentialsMatcher會自動(dòng)識別這個(gè)鹽。 

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

Java代碼  

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

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

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

此處還要注意Shiro默認(rèn)使用了apache commons BeanUtils,默認(rèn)是不進(jìn)行Enum類型轉(zhuǎn)型的,此時(shí)需要自己注冊一個(gè)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)

Java代碼  

[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 

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

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

3、credentialsMatcher.storedCredentialsHexEncoded=true表示是否存儲散列后的密碼為16進(jìn)制,需要和生成密碼時(shí)的一樣,默認(rèn)是base64; 

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

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

密碼重試次數(shù)限制

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

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

Java代碼  

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中的重試次數(shù)+1,如果超出5次那么拋出異常表示超出重試次數(shù)了。

總結(jié)

以上所述是小編給大家介紹的shiro編碼和加密,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

  • Java 中Json中既有對象又有數(shù)組的參數(shù)如何轉(zhuǎn)化成對象(推薦)

    Java 中Json中既有對象又有數(shù)組的參數(shù)如何轉(zhuǎn)化成對象(推薦)

    Gson庫是一個(gè)功能強(qiáng)大、易于使用的Java序列化/反序列化庫,它提供了豐富的API來支持Java對象和JSON之間的轉(zhuǎn)換,這篇文章主要介紹了Java 中Json中既有對象又有數(shù)組的參數(shù)如何轉(zhuǎn)化成對象,需要的朋友可以參考下
    2024-07-07
  • Springboot mybatis plus druid多數(shù)據(jù)源解決方案 dynamic-datasource的使用詳解

    Springboot mybatis plus druid多數(shù)據(jù)源解決方案 dynamic-datasource的使用詳

    這篇文章主要介紹了Springboot mybatis plus druid多數(shù)據(jù)源解決方案 dynamic-datasource的使用,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • Java實(shí)現(xiàn)公用實(shí)體類轉(zhuǎn)Tree結(jié)構(gòu)

    Java實(shí)現(xiàn)公用實(shí)體類轉(zhuǎn)Tree結(jié)構(gòu)

    這篇文章主要為大家介紹了一個(gè)Java工具類,可以實(shí)現(xiàn)Java公用實(shí)體類轉(zhuǎn)Tree結(jié)構(gòu),文中的示例代碼簡潔易懂,感興趣的小伙伴可以參考一下
    2024-10-10
  • Java源碼解析重寫鎖的設(shè)計(jì)結(jié)構(gòu)和細(xì)節(jié)

    Java源碼解析重寫鎖的設(shè)計(jì)結(jié)構(gòu)和細(xì)節(jié)

    這篇文章主要為大家介紹了Java源碼解析重寫鎖的設(shè)計(jì)結(jié)構(gòu)和細(xì)節(jié),這小節(jié)我們以共享鎖作為案列,自定義一個(gè)共享鎖。有需要的朋友可以借鑒參考下
    2022-03-03
  • Mybatis-plus如何查詢表中指定字段(不查詢?nèi)孔侄?

    Mybatis-plus如何查詢表中指定字段(不查詢?nèi)孔侄?

    這篇文章主要介紹了Mybatis-plus如何查詢表中指定字段(不查詢?nèi)孔侄?,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • Java設(shè)計(jì)模式之java裝飾者模式詳解

    Java設(shè)計(jì)模式之java裝飾者模式詳解

    這篇文章主要為大家詳細(xì)介紹了java設(shè)計(jì)模式之裝飾者模式,裝飾者模式是一種結(jié)構(gòu)式模式,感興趣的朋友可以參考一下,希望能夠給你帶來幫助
    2021-09-09
  • Java 方法遞歸的思路詳解

    Java 方法遞歸的思路詳解

    程序調(diào)用自身的編程技巧稱為遞歸( recursion)。遞歸做為一種算法在程序設(shè)計(jì)語言中廣泛應(yīng)用。但是如果沒終止條件會造成死循環(huán),所以遞歸代碼里要有結(jié)束自調(diào)自的條件,接下來講解一下學(xué)習(xí)遞歸的思路
    2022-04-04
  • Java編程中利用InetAddress類確定特殊IP地址的方法

    Java編程中利用InetAddress類確定特殊IP地址的方法

    這篇文章主要介紹了Java編程中利用InetAddress類確定特殊IP地址的方法,InetAddress類是Java網(wǎng)絡(luò)編程中一個(gè)相當(dāng)實(shí)用的類,需要的朋友可以參考下
    2015-11-11
  • Spring Boot整合swagger使用教程詳解

    Spring Boot整合swagger使用教程詳解

    這篇文章主要介紹了Spring Boot整合swagger使用教程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-07-07
  • JDK14的新特性NullPointerExceptions的使用

    JDK14的新特性NullPointerExceptions的使用

    這篇文章主要介紹了JDK14的新特性NullPointerExceptions的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04

最新評論