shiro中雜湊的相關知識
在我們初期的學習中,我們存入資料庫的賬號和密碼大多都是以明文的形式存在,很明顯它雖然操作簡單,但是對於其他人來說也是很容易就獲取到的,所以這裡我們學習一個新的知識,在shiro中用來儲存一些敏感資訊,即MD5Hash。
1、首先了解加鹽雜湊和雜湊關係, 瞭解為什麼要加鹽?
給這個密碼再新增一層保障 為了讓密碼更加安全 更加不容易被破解
public static void main(String[] args){
// Md5Hash md5Hash = new Md5Hash(“abc”);
//
// System。out。println(“雜湊後的結果:”+md5Hash);
Md5Hash md5Hash1 = new Md5Hash(“abc”, “123”);
System。out。println(“加鹽雜湊之後的值:”+md5Hash1);
Md5Hash md5Hash2 = new Md5Hash(“123abc”);
System。out。println(“加鹽雜湊之後的值:”+md5Hash2);
//再看下多次雜湊的問題
Md5Hash md5Hash = new Md5Hash(“123”, “”, 2);
System。out。println(“加鹽+次數構成的值:”+md5Hash);
Md5Hash md5Hash3 = new Md5Hash(“123”);
Md5Hash md5Hash4 = new Md5Hash(md5Hash3);
System。out。println(“翻譯後的值:”+md5Hash4);
}
2、realm中雜湊的例子
2
。
1
先將密碼改為加鹽雜湊後的值
Md5Hash
md5Hash1
=
new
Md5Hash
(
“123”
,
“abc”
);
System
。
out
。
println
(
“加鹽雜湊之後的值:”
+
md5Hash1
);
2
。
2
編寫realm
public
class
MyRealm
extends
AuthorizingRealm
{
private
UserDAO
userDAO
=
new
UserDAO
();
@Override
public
String
getName
()
{
return
“MyRealm”
;
}
/**
*這個方法是用來進行認證的
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected
AuthenticationInfo
doGetAuthenticationInfo
(
AuthenticationToken
authenticationToken
)
throws
AuthenticationException
{
//第一步:透過token獲取到使用者資料
String
userName
=
(
String
)
authenticationToken
。
getPrincipal
();
//第二步:透過使用者名稱 去資料庫查詢使用者物件
User
user
=
null
;
try
{
user
=
userDAO
。
findUserByName
(
userName
);
System
。
out
。
println
(
“從資料庫查詢出來的資料是:”
+
user
);
}
catch
(
Exception
e
)
{
System
。
out
。
println
(
“查詢失敗:”
+
e
。
fillInStackTrace
());
}
if
(
null
==
user
){
//說明資料庫裡面沒有查詢出資料來
return
null
;
}
//使用者資訊查詢出來了
//User user = new User(1, “xiaobobo”, “123”);
// SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user。getUserName(),user。getPassword(),getName());
SimpleAuthenticationInfo
simpleAuthenticationInfo
=
new
SimpleAuthenticationInfo
(
user
。
getUserName
(),
//使用者名稱
user
。
getPassword
(),
//密碼
ByteSource
。
Util
。
bytes
(
user
。
getSalt
()),
//這個是從資料庫獲取的鹽
getName
());
//realm的名字
return
simpleAuthenticationInfo
;
}
/**
* 做使用者授權的
* @param principalCollection
* @return
*/
@Override
protected
AuthorizationInfo
doGetAuthorizationInfo
(
PrincipalCollection
principalCollection
)
{
return
null
;
}
}
2
。
3
編寫配置檔案
[
main
]
#
定義憑證匹配器
credentialsMatcher
=
org
。
apache
。
shiro
。
authc
。
credential
。
HashedCredentialsMatcher
#
雜湊演算法
credentialsMatcher
。
hashAlgorithmName
=
md5
#
雜湊次數
credentialsMatcher
。
hashIterations
=
1
#
將憑證匹配器設定到realm
customRealm
=
com
。
qf
。
shiro
。
md5
。
MyRealm
customRealm
。
credentialsMatcher
=
$credentialsMatcher
securityManager
。
realms
=
$customRealm
2
。
4
執行測試
上一篇:周朝分封的八大公爵諸侯國