使用google身份驗證器實現動態口令驗證


最近有用戶反應我們現有的短信+郵件驗證,不安全及短信條數限制和郵件收驗證碼比較慢的問題,希望我們

也能做一個類似銀行動態口令的驗證方式。經過對可行性的分析及慎重考慮,可以實現一個這樣的功能。

怎么實現呢,是自己開發一個這樣的app?這樣成本太高了,為了節約成本,我們使用互聯網使用比較多的google

身份驗證器。使用它,我們只需要開發服務端就可以了。

google身份驗證器的原理是什么呢?客戶端和服務器事先協商好一個密鑰K,用於一次性密碼的生成過程,此

密鑰不被任何第三方所知道。此外,客戶端和服務器各有一個計數器C,並且事先將計數值同步。進行驗證時,客戶端對

密鑰和計數器的組合(K,C)使用HMAC(Hash-based Message Authentication Code)算法計算一次性密碼,公式如下:

 

[java] view plain  copy
 
  1. HOTP(K,C) = Truncate(HMAC-SHA-1(K,C))  

 

上面采用了HMAC-SHA-1,當然也可以使用HMAC-MD5等。HMAC算法得出的值位數比較多,不方便用戶輸入,因

此需要截斷(Truncate)成為一組不太長十進制數(例如6位)。計算完成之后客戶端計數器C計數值加1。用戶將這一組十

進制數輸入並且提交之后,服務器端同樣的計算,並且與用戶提交的數值比較,如果相同,則驗證通過,服務器端將計數值

C增加1。如果不相同,則驗證失敗。

Java服務端實現代碼:板面的做法和配料

 

[java] view plain  copy
 
  1. package com.auth.google;  
  2.   
  3. import java.security.InvalidKeyException;  
  4. import java.security.NoSuchAlgorithmException;  
  5. import java.security.SecureRandom;  
  6. import javax.crypto.Mac;  
  7. import javax.crypto.spec.SecretKeySpec;  
  8. import org.apache.commons.codec.binary.Base32;  
  9. import org.apache.commons.codec.binary.Base64;  
  10.   
  11. /** 
  12.  *  
  13.  *  
  14.  * google身份驗證器,java服務端實現 
  15.  *  
  16.  * @author yangbo 
  17.  *  
  18.  * @version 創建時間:2017年8月14日 上午10:10:02 
  19.  * 
  20.  *  
  21.  */  
  22. public class GoogleAuthenticator {  
  23.   
  24.     // 生成的key長度( Generate secret key length)  
  25.     public static final int SECRET_SIZE = 10;  
  26.   
  27.     public static final String SEED = "g8GjEvTbW5oVSV7avL47357438reyhreyuryetredLDVKs2m0QN7vxRs2im5MDaNCWGmcD2rvcZx";  
  28.     // Java實現隨機數算法  
  29.     public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";  
  30.     // 最多可偏移的時間  
  31.     int window_size = 3; // default 3 - max 17  
  32.   
  33.     /** 
  34.      * set the windows size. This is an integer value representing the number of 
  35.      * 30 second windows we allow The bigger the window, the more tolerant of 
  36.      * clock skew we are. 
  37.      *  
  38.      * @param s 
  39.      *            window size - must be >=1 and <=17. Other values are ignored 
  40.      */  
  41.     public void setWindowSize(int s) {  
  42.         if (s >= 1 && s <= 17)  
  43.             window_size = s;  
  44.     }  
  45.   
  46.     /** 
  47.      * Generate a random secret key. This must be saved by the server and 
  48.      * associated with the users account to verify the code displayed by Google 
  49.      * Authenticator. The user must register this secret on their device. 
  50.      * 生成一個隨機秘鑰 
  51.      *  
  52.      * @return secret key 
  53.      */  
  54.     public static String generateSecretKey() {  
  55.         SecureRandom sr = null;  
  56.         try {  
  57.             sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);  
  58.             sr.setSeed(Base64.decodeBase64(SEED));  
  59.             byte[] buffer = sr.generateSeed(SECRET_SIZE);  
  60.             Base32 codec = new Base32();  
  61.             byte[] bEncodedKey = codec.encode(buffer);  
  62.             String encodedKey = new String(bEncodedKey);  
  63.             return encodedKey;  
  64.         } catch (NoSuchAlgorithmException e) {  
  65.             // should never occur... configuration error  
  66.         }  
  67.         return null;  
  68.     }  
  69.   
  70.     /** 
  71.      * Return a URL that generates and displays a QR barcode. The user scans 
  72.      * this bar code with the Google Authenticator application on their 
  73.      * smartphone to register the auth code. They can also manually enter the 
  74.      * secret if desired 
  75.      *  
  76.      * @param user 
  77.      *            user id (e.g. fflinstone) 
  78.      * @param host 
  79.      *            host or system that the code is for (e.g. myapp.com) 
  80.      * @param secret 
  81.      *            the secret that was previously generated for this user 
  82.      * @return the URL for the QR code to scan 
  83.      */  
  84.     public static String getQRBarcodeURL(String user, String host, String secret) {  
  85.         String format = "http://www.google.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=otpauth://totp/%s@%s?secret=%s";  
  86.         return String.format(format, user, host, secret);  
  87.     }  
  88.   
  89.     /** 
  90.      * 生成一個google身份驗證器,識別的字符串,只需要把該方法返回值生成二維碼掃描就可以了。 
  91.      *  
  92.      * @param user 
  93.      *            賬號 
  94.      * @param secret 
  95.      *            密鑰 
  96.      * @return 
  97.      */  
  98.     public static String getQRBarcode(String user, String secret) {  
  99.         String format = "otpauth://totp/%s?secret=%s";  
  100.         return String.format(format, user, secret);  
  101.     }  
  102.   
  103.     /** 
  104.      * Check the code entered by the user to see if it is valid 驗證code是否合法 
  105.      *  
  106.      * @param secret 
  107.      *            The users secret. 
  108.      * @param code 
  109.      *            The code displayed on the users device 
  110.      * @param t 
  111.      *            The time in msec (System.currentTimeMillis() for example) 
  112.      * @return 
  113.      */  
  114.     public boolean check_code(String secret, long code, long timeMsec) {  
  115.         Base32 codec = new Base32();  
  116.         byte[] decodedKey = codec.decode(secret);  
  117.         // convert unix msec time into a 30 second "window"  
  118.         // this is per the TOTP spec (see the RFC for details)  
  119.         long t = (timeMsec / 1000L) / 30L;  
  120.         // Window is used to check codes generated in the near past.  
  121.         // You can use this value to tune how far you're willing to go.  
  122.         for (int i = -window_size; i <= window_size; ++i) {  
  123.             long hash;  
  124.             try {  
  125.                 hash = verify_code(decodedKey, t + i);  
  126.             } catch (Exception e) {  
  127.                 // Yes, this is bad form - but  
  128.                 // the exceptions thrown would be rare and a static  
  129.                 // configuration problem  
  130.                 e.printStackTrace();  
  131.                 throw new RuntimeException(e.getMessage());  
  132.                 // return false;  
  133.             }  
  134.             if (hash == code) {  
  135.                 return true;  
  136.             }  
  137.         }  
  138.         // The validation code is invalid.  
  139.         return false;  
  140.     }  
  141.   
  142.     private static int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {  
  143.         byte[] data = new byte[8];  
  144.         long value = t;  
  145.         for (int i = 8; i-- > 0; value >>>= 8) {  
  146.             data[i] = (byte) value;  
  147.         }  
  148.         SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");  
  149.         Mac mac = Mac.getInstance("HmacSHA1");  
  150.         mac.init(signKey);  
  151.         byte[] hash = mac.doFinal(data);  
  152.         int offset = hash[20 - 1] & 0xF;  
  153.         // We're using a long because Java hasn't got unsigned int.  
  154.         long truncatedHash = 0;  
  155.         for (int i = 0; i < 4; ++i) {  
  156.             truncatedHash <<= 8;  
  157.             // We are dealing with signed bytes:  
  158.             // we just keep the first byte.  
  159.             truncatedHash |= (hash[offset + i] & 0xFF);  
  160.         }  
  161.         truncatedHash &= 0x7FFFFFFF;  
  162.         truncatedHash %= 1000000;  
  163.         return (int) truncatedHash;  
  164.     }  
  165. }  

 

 

測試代碼:

 

[java] view plain  copy
 
  1. package com.auth.google;  
  2.   
  3. import org.junit.Test;  
  4.   
  5. /** 
  6.  *  
  7.  *  
  8.  * 身份認證測試 
  9.  *  
  10.  * @author yangbo 
  11.  *  
  12.  * @version 創建時間:2017年8月14日 上午11:09:23 
  13.  * 
  14.  *  
  15.  */  
  16. public class AuthTest {  
  17.     //當測試authTest時候,把genSecretTest生成的secret值賦值給它  
  18.     private static String secret="R2Q3S52RNXBTFTOM";  
  19.   
  20.     //@Test  
  21.     public void genSecretTest() {// 生成密鑰  
  22.          secret = GoogleAuthenticator.generateSecretKey();  
  23.         // 把這個qrcode生成二維碼,用google身份驗證器掃描二維碼就能添加成功  
  24.         String qrcode = GoogleAuthenticator.getQRBarcode("2816661736@qq.com", secret);  
  25.         System.out.println("qrcode:" + qrcode + ",key:" + secret);  
  26.     }  
  27.     /** 
  28.      * 對app的隨機生成的code,輸入並驗證 
  29.      */  
  30.      @Test  
  31.     public void verifyTest() {  
  32.         long code = 807337;  
  33.         long t = System.currentTimeMillis();  
  34.         GoogleAuthenticator ga = new GoogleAuthenticator();  
  35.         ga.setWindowSize(5);   
  36.         boolean r = ga.check_code(secret, code, t);  
  37.         System.out.println("檢查code是否正確?" + r);  
  38.     }  
  39. }  

 

 

具體使用方式(iOS演示):

第一步:進入iphone的appstore,在搜索框中輸入google身份驗證器,如下圖:

 

選擇上圖中的google authenticator 並安裝。

第二步:運行下面鏈接中下載的demo中的AuthTest的genSecretTest方法,控制台打印的結果如下圖:

key:為app與服務端約定的秘鑰,用於雙方的認證。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM