MD5加密详解
MD5加密詳解
加密過程:
密碼:123456 (明文形式)----->加密后 49ba59abbe56e057
1.密碼在請求提交后到達控制器
2.到達控制后通過加密規(guī)則,轉(zhuǎn)換成密文
3.在經(jīng)過DAO查詢與數(shù)據(jù)庫中已經(jīng)存在的密文密碼比對是否一直,一致,則放行。
-
用戶注冊密碼時是加密存儲的
-
用戶修改密碼時,也需要進行加密存儲
加密規(guī)則:
-
加密規(guī)則可以自定義,在項目中通常使用BASE64和MD5,本文使用的加密規(guī)則就是MD5,
-
BASE64: 可反編碼的編碼方式
? 明文—密文
? 密文–明文
-
MD5:不可逆的編碼方式 (非對稱)
明文----密文
-
如果數(shù)據(jù)庫用戶的密碼儲存的密文,Shiro如何完成驗證?
-
使用Shiro提供的加密功能,對輸入的密碼進行加密后在進行確認。
Shiro使用加密認證
配置matcher
@Configuration public class ShiroConfig {//...@Beanpublic HashedCredentialsMatcher getHashedCredentialsMatcher(){HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();//matcher就是用來指定加密規(guī)則//加密方式matcher.setHashAlgorithmName("md5");//hash次數(shù)matcher.setHashIterations(1); //此處的循環(huán)次數(shù)要與用戶注冊是密碼加密次數(shù)一致return matcher;}//自定義Realm@Beanpublic MyRealm getMyRealm( HashedCredentialsMatcher matcher ){MyRealm myRealm = new MyRealm();myRealm.setCredentialsMatcher(matcher);return myRealm;}//... }用戶密碼加密處理
-
UserComtroller
@Controller @RequestMapping("user") public class UserController {@Resourceprivate UserServiceImpl userService;@RequestMapping("/regist")public String regist(String userName,String userPwd) {System.out.println("------注冊");//注冊的時候要對密碼進行加密存儲Md5Hash md5Hash = new Md5Hash(userPwd);System.out.println("--->>>"+ md5Hash.toHex());//加鹽加密int num = new Random().nextInt(90000)+10000; //10000—99999String salt = num+"";Md5Hash md5Hash2 = new Md5Hash(userPwd,salt);System.out.println("--->>>"+md5Hash2);//加鹽加密+多次hashMd5Hash md5Hash3 = new Md5Hash(userPwd,salt,3);System.out.println("--->>>"+md5Hash3);//SimpleHash hash = new SimpleHash("md5",userPwd,num,3);//將用戶信息保存到數(shù)據(jù)庫時,保存加密后的密碼,如果生成的隨機鹽,鹽也要保存return "login";}}
-
加鹽處理
-
在自定義Realm中:
/*** 獲取認證的安全數(shù)據(jù)(從數(shù)據(jù)庫查詢的用戶的正確數(shù)據(jù))*/protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {//參數(shù)authenticationToken就是傳遞的 subject.login(token)// 從token中獲取用戶名UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;String username = token.getUsername();//根據(jù)用戶名,從數(shù)據(jù)庫查詢當前用戶的安全數(shù)據(jù)User user = userDAO.queryUserByUsername(username);// AuthenticationInfo info = new SimpleAuthenticationInfo( // username, //當前用戶用戶名 // user.getUserPwd(), //從數(shù)據(jù)庫查詢出來的安全密碼 // getName());//如果數(shù)據(jù)庫中用戶的密碼是加了鹽的AuthenticationInfo info = new SimpleAuthenticationInfo(username, //當前用戶用戶名user.getUserPwd(), //從數(shù)據(jù)庫查詢出來的安全密碼ByteSource.Util.bytes(user.getPwdSalt()),getName());return info;} }
總結
- 上一篇: 关于c# .net爬虫
- 下一篇: Decorator模式