1.爲什麼要加密?採用什麼算法加密?
加密主要是保護用戶的安全。一般採用非對稱加密,一種不可逆的算法。把加密的密碼存儲後,再把客戶端傳來的密碼加密後和數據庫中加密的密碼進行比較是否相同
2.加密的流程如下圖:
在shiro中
3.user對象
public class User {
private int id;
private String name;
private String password;
private String salt;
//get和set方法
}
4.DAO對象的create方法
public class DAO{
//註冊用戶
public void creatUser(String userName, String password){
String sql = "insert into t_user values(null,?,?,?)";
//產生一個鹽值
String salt = new SecureRandomNumberGenerator().nextBytes().toString();
//加密
String encodePassWord = new SimpleHash("md5", password, salt,2).toString();
//user.setPassword(encodePassWord)
//把user對象存儲到數據庫中
}
5.Realm的doGetAuthenticationInfo()方法
public class MyRealm extends AuthorizingRealm{
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//獲取賬號密碼
UsernamePasswordToken t = (UsernamePasswordToken) token;
String userName= token.getPrincipal().toString();
String password =new String(t.getPassword());
//獲取數據庫中的密碼
User user = new DAO().getUser(userName);
String passwordInDB = user.getPassword();
String salt = user.getSalt();
//把客戶端的密碼加密
String passwordEncoded = new SimpleHash("md5",password,salt,2).toString();
if(null==user || !passwordEncoded.equals(passwordInDB))
throw new AuthenticationException();
//認證信息裏存放賬號密碼, getName() 是當前Realm的繼承方法,通常返回當前類名 :databaseRealm
SimpleAuthenticationInfo a = new SimpleAuthenticationInfo(userName,password,getName());
return a;
}
}
6.test測試
subject.login(token); //true 爲認證成功 false認證失敗。
7.其實在shiro框架中可以幫助我們自動把客戶端的源碼加密,再和數據庫中的密碼進行比較。
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//獲取賬號和密碼
System.out.println(this.getCredentialsMatcher());
UsernamePasswordToken t = (UsernamePasswordToken)token;
String userName = t.getPrincipal().toString();
User user = new Db().getUser1(userName);
String passwordDB = user.getPassword();
String salt = user.getSalt();
//傳入從數據庫查詢的密碼和鹽值
return new SimpleAuthenticationInfo(userName,passwordDB,ByteSource.Util.bytes(salt),getName());
}
談到自動,就需要配置shiro.ini文件
[main]
#設置加密算法,加密次數,十六進制存儲
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
credentialsMatcher.hashAlgorithmName=md5
credentialsMatcher.hashIterations=2
credentialsMatcher.storedCredentialsHexEncoded=true
databaseRealm=com.shiro.pojo.DatabaseRealm
databaseRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$databaseRealm