使用Apache Shiro進行身份認證-密碼加密

來源:互聯網
上載者:User

在進行身份認證時,使用者的密碼一般是用密文的形式存放在資料庫中。這樣在做比對時不能直接使用使用者提交的明文口令。

在Shiro中使用org.apache.shiro.authc.credential.SimpleCredentialsMatcher做憑證資訊的比對。SimpleCredentialsMatcher實現了

憑證資訊的明文比對,即對憑證資訊不做任何處理。

通過HashedCredentialsMatcher子類的擴充Shiro支援一些標準的密碼編譯演算法,如MD5 和 SHA-1。

在使用時也可以根據自身需求定義自己的密碼編譯演算法。下面是我實現的憑證資訊比對類,密碼編譯演算法是在網上找的DES演算法。

public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {@Overridepublic boolean doCredentialsMatch(AuthenticationToken token,AuthenticationInfo info) {Object tokenCredentials = encrypt(toBytes(token.getCredentials()));Object accountCredentials = getCredentials(info);return equals(tokenCredentials, accountCredentials);}private byte[] encrypt(byte[] data) {try {byte[] key = "11111111".getBytes();// DES演算法要求有一個可信任的隨機數源SecureRandom sr = new SecureRandom();// 從原始密鑰資料建立DESKeySpec對象DESKeySpec dks = new DESKeySpec(key);// 建立一個密匙工廠,然後用它把DESKeySpec轉換成// 一個SecretKey對象SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey secretKey = keyFactory.generateSecret(dks);// using DES in ECB modeCipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");// 用密匙初始化Cipher對象cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);// 執行加密操作byte encryptedData[] = cipher.doFinal(data);return encryptedData;} catch (Exception e) {System.err.println("DES演算法,加密資料出錯!");e.printStackTrace();}return null;}}

使用時在Shiro.ini檔案中加上這個類:

[main]customMatcher = main.java.name.peter.shiro.realm.CustomCredentialsMatcherjdbcRealm.credentialsMatcher = $customMatcher



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.