Google Authenticator 原理及Java实现

作者:徐小花
链接:https://www.zhihu.com/question/20462696/answer/18731073
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

开启Google的登陆二步验证(即Google Authenticator服务)后用户登陆时需要输入额外由手机客户端生成的一次性密码。

实现Google Authenticator功能需要服务器端和客户端的支持。服务器端负责密钥的生成、验证一次性密码是否正确。客户端记录密钥后生成一次性密码。

目前客户端有:
android版: Google 身份验证器
iOS版: itunes.apple.com/cn/app

实现原理:

一、用户需要开启Google Authenticator服务时,
1.服务器随机生成一个类似于『DPI45HKISEXU6HG7』的密钥,并且把这个密钥保存在数据库中。
2.在页面上显示一个二维码,内容是一个URI地址(otpauth://totp/账号?secret=密钥),如『otpauth://totp/kisexu@gmail.com?secret=DPI45HCEBCJK6HG7』,下图:

otpauth://totp/kisexu@gmail.com?secret=DPI45HCEBCJK6HG7 (二维码自动识别)


3.客户端扫描二维码,把密钥『DPI45HKISEXU6HG7』保存在客户端。

二、用户需要登陆时
1.客户端每30秒使用密钥『DPI45HKISEXU6HG7』和时间戳通过一种『算法』生成一个6位数字的一次性密码,如『684060』。如下图android版界面:
<img src="https://i-blog.csdnimg.cn/blog_migrate/454d5e85e958f14af1520d63b2977c4e.png" data-rawwidth="281" data-rawheight="398" class="content_image" width="281">
2.用户登陆时输入一次性密码『684060』。
3.服务器端使用保存在数据库中的密钥『DPI45HKISEXU6HG7』和时间戳通过同一种『算法』生成一个6位数字的一次性密码。大家都懂控制变量法,如果算法相同、密钥相同,又是同一个时间(时间戳相同),那么客户端和服务器计算出的一次性密码是一样的。服务器验证时如果一样,就登录成功了。

Tips:
1.这种『算法』是公开的,所以服务器端也有很多开源的实现,比如php版的: github.com/PHPGangsta/G 。上github搜索『Google Authenticator』可以找到更多语言版的Google Authenticator。
2.所以,你在自己的项目可以轻松加入对Google Authenticator的支持,在一个客户端上显示多个账户的效果可以看上面android版界面的截图。目前dropbox、lastpass、wordpress,甚至vps等第三方应用都支持Google Authenticator登陆,请自行搜索。
3.现实生活中,网银、网络游戏的实体动态口令牌其实原理也差不多,大家可以自行脑补下,谢谢。

示例url:
https://www.google.com/chart?chs=200x200&chld=M%7C0&cht=qr&chl=otpauth://totp/testuser@testhost%3Fsecret%3DIV5H5FGFJS6K4N2Y
-------------------------------------------
链接:http://blog.youkuaiyun.com/a623397674a/article/details/38336461
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


  1. //Google  Authenticator  
  2.   
  3. // 只从google出了双重身份验证后,就方便了大家,等同于有了google一个级别的安全,但是我们该怎么使用google authenticator (双重身份验证),  
  4.   
  5. //下面是java的算法,这样大家都可以得到根据key得到公共的秘钥了,直接复制,记得导入JAR包:  
  6. //  
  7. //commons-codec-1.8.jar  
  8. //  
  9. //junit-4.10.jar  
  10.   
  11.   
  12. //测试方法:  
  13. //  
  14. //1、执行测试代码中的“genSecret”方法,将生成一个KEY(用户为testuser),URL打开是一张二维码图片。  
  15. //  
  16. //2、在手机中下载“GOOGLE身份验证器”。  
  17. //  
  18. //3、在身份验证器中配置账户,输入账户名(第一步中的用户testuser)、密钥(第一步生成的KEY),选择基于时间。  
  19. //  
  20. //4、运行authcode方法将key和要测试的验证码带进去(codes,key),就可以知道是不是正确的秘钥了!返回值布尔  
  21.   
  22. //main我就不写了大家~~因为这个可以当做util工具直接调用就行了  
  23. //  
  24.   
  25. package coin.util;  
  26.   
  27. import java.security.InvalidKeyException;  
  28. import java.security.NoSuchAlgorithmException;  
  29. import java.security.SecureRandom;  
  30.   
  31. import javax.crypto.Mac;  
  32. import javax.crypto.spec.SecretKeySpec;  
  33.   
  34. import org.apache.commons.codec.binary.Base32;  
  35. import org.apache.commons.codec.binary.Base64;  
  36.   
  37.   
  38.   
  39. public class GoogleAuthenticator {  
  40.       
  41.     // taken from Google pam docs - we probably don't need to mess with these  
  42.     public static final int SECRET_SIZE = 10;  
  43.       
  44.     public static final String SEED = "g8GjEvTbW5oVSV7avLBdwIHqGlUYNzKFI7izOF8GwLDVKs2m0QN7vxRs2im5MDaNCWGmcD2rvcZx";  
  45.       
  46.     public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";  
  47.       
  48.     int window_size = 3// default 3 - max 17 (from google docs)最多可偏移的时间  
  49.     
  50.     public void setWindowSize(int s) {  
  51.         if (s >= 1 && s <= 17)  
  52.             window_size = s;  
  53.     }  
  54.       
  55.    
  56.       
  57.     public static Boolean authcode(String codes, String savedSecret) {  
  58.         // enter the code shown on device. Edit this and run it fast before the  
  59.         // code expires!  
  60.         long code = Long.parseLong(codes);  
  61.         long t = System.currentTimeMillis();  
  62.         GoogleAuthenticator ga = new GoogleAuthenticator();  
  63.         ga.setWindowSize(15); // should give 5 * 30 seconds of grace...  
  64.         boolean r = ga.check_code(savedSecret, code, t);  
  65.         return r;  
  66.     }  
  67.     public static String genSecret() {  
  68.         String secret = GoogleAuthenticator.generateSecretKey();  
  69.         GoogleAuthenticator.getQRBarcodeURL("testuser",  
  70.                 "testhost", secret);  
  71.         return secret;  
  72.     }  
  73.     public static String generateSecretKey() {  
  74.         SecureRandom sr = null;  
  75.         try {  
  76.             sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);  
  77.             sr.setSeed(Base64.decodeBase64(SEED));  
  78.             byte[] buffer = sr.generateSeed(SECRET_SIZE);  
  79.             Base32 codec = new Base32();  
  80.             byte[] bEncodedKey = codec.encode(buffer);  
  81.             String encodedKey = new String(bEncodedKey);  
  82.             return encodedKey;  
  83.         }catch (NoSuchAlgorithmException e) {  
  84.             // should never occur... configuration error  
  85.         }  
  86.         return null;  
  87.     }  
  88.       
  89.    
  90.     public static String getQRBarcodeURL(String user, String host, String secret) {  
  91.         String format = "https://www.google.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=otpauth://totp/%s@%s%%3Fsecret%%3D%s";  
  92.         return String.format(format, user, host, secret);  
  93.     }  
  94.       
  95.   
  96.     public boolean check_code(String secret, long code, long timeMsec) {  
  97.         Base32 codec = new Base32();  
  98.         byte[] decodedKey = codec.decode(secret);  
  99.         // convert unix msec time into a 30 second "window"  
  100.         // this is per the TOTP spec (see the RFC for details)  
  101.         long t = (timeMsec / 1000L) / 30L;  
  102.         // Window is used to check codes generated in the near past.  
  103.         // You can use this value to tune how far you're willing to go.  
  104.         for (int i = -window_size; i <= window_size; ++i) {  
  105.             long hash;  
  106.             try {  
  107.                 hash = verify_code(decodedKey, t + i);  
  108.             }catch (Exception e) {  
  109.                 // Yes, this is bad form - but  
  110.                 // the exceptions thrown would be rare and a static configuration problem  
  111.                 e.printStackTrace();  
  112.                 throw new RuntimeException(e.getMessage());  
  113.                 //return false;  
  114.             }  
  115.             if (hash == code) {  
  116.                 return true;  
  117.             }  
  118.         }  
  119.         // The validation code is invalid.  
  120.         return false;  
  121.     }  
  122.       
  123.     private static int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {  
  124.         byte[] data = new byte[8];  
  125.         long value = t;  
  126.         for (int i = 8; i-- > 0; value >>>= 8) {  
  127.             data[i] = (byte) value;  
  128.         }  
  129.         SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");  
  130.         Mac mac = Mac.getInstance("HmacSHA1");  
  131.         mac.init(signKey);  
  132.         byte[] hash = mac.doFinal(data);  
  133.         int offset = hash[20 - 1] & 0xF;  
  134.         // We're using a long because Java hasn't got unsigned int.  
  135.         long truncatedHash = 0;  
  136.         for (int i = 0; i < 4; ++i) {  
  137.             truncatedHash <<= 8;  
  138.             // We are dealing with signed bytes:  
  139.             // we just keep the first byte.  
  140.             truncatedHash |= (hash[offset + i] & 0xFF);  
  141.         }  
  142.         truncatedHash &= 0x7FFFFFFF;  
  143.         truncatedHash %= 1000000;  
  144.         return (int) truncatedHash;  
  145.     }  
  146. }  
//Google  Authenticator

// 只从google出了双重身份验证后,就方便了大家,等同于有了google一个级别的安全,但是我们该怎么使用google authenticator (双重身份验证),

//下面是java的算法,这样大家都可以得到根据key得到公共的秘钥了,直接复制,记得导入JAR包:
//
//commons-codec-1.8.jar
//
//junit-4.10.jar


//测试方法:
//
//1、执行测试代码中的“genSecret”方法,将生成一个KEY(用户为testuser),URL打开是一张二维码图片。
//
//2、在手机中下载“GOOGLE身份验证器”。
//
//3、在身份验证器中配置账户,输入账户名(第一步中的用户testuser)、密钥(第一步生成的KEY),选择基于时间。
//
//4、运行authcode方法将key和要测试的验证码带进去(codes,key),就可以知道是不是正确的秘钥了!返回值布尔

//main我就不写了大家~~因为这个可以当做util工具直接调用就行了
//

package coin.util;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base32;
import org.apache.commons.codec.binary.Base64;



public class GoogleAuthenticator {
    
    // taken from Google pam docs - we probably don't need to mess with these
    public static final int SECRET_SIZE = 10;
    
    public static final String SEED = "g8GjEvTbW5oVSV7avLBdwIHqGlUYNzKFI7izOF8GwLDVKs2m0QN7vxRs2im5MDaNCWGmcD2rvcZx";
    
    public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";
    
    int window_size = 3; // default 3 - max 17 (from google docs)最多可偏移的时间
  
    public void setWindowSize(int s) {
        if (s >= 1 && s <= 17)
            window_size = s;
    }
    
 
    
    public static Boolean authcode(String codes, String savedSecret) {
        // enter the code shown on device. Edit this and run it fast before the
        // code expires!
        long code = Long.parseLong(codes);
        long t = System.currentTimeMillis();
        GoogleAuthenticator ga = new GoogleAuthenticator();
        ga.setWindowSize(15); // should give 5 * 30 seconds of grace...
        boolean r = ga.check_code(savedSecret, code, t);
        return r;
    }
    public static String genSecret() {
        String secret = GoogleAuthenticator.generateSecretKey();
        GoogleAuthenticator.getQRBarcodeURL("testuser",
                "testhost", secret);
        return secret;
    }
    public static String generateSecretKey() {
        SecureRandom sr = null;
        try {
            sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);
            sr.setSeed(Base64.decodeBase64(SEED));
            byte[] buffer = sr.generateSeed(SECRET_SIZE);
            Base32 codec = new Base32();
            byte[] bEncodedKey = codec.encode(buffer);
            String encodedKey = new String(bEncodedKey);
            return encodedKey;
        }catch (NoSuchAlgorithmException e) {
            // should never occur... configuration error
        }
        return null;
    }
    
 
    public static String getQRBarcodeURL(String user, String host, String secret) {
        String format = "https://www.google.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=otpauth://totp/%s@%s%%3Fsecret%%3D%s";
        return String.format(format, user, host, secret);
    }
    

    public boolean check_code(String secret, long code, long timeMsec) {
        Base32 codec = new Base32();
        byte[] decodedKey = codec.decode(secret);
        // convert unix msec time into a 30 second "window"
        // this is per the TOTP spec (see the RFC for details)
        long t = (timeMsec / 1000L) / 30L;
        // Window is used to check codes generated in the near past.
        // You can use this value to tune how far you're willing to go.
        for (int i = -window_size; i <= window_size; ++i) {
            long hash;
            try {
                hash = verify_code(decodedKey, t + i);
            }catch (Exception e) {
                // Yes, this is bad form - but
                // the exceptions thrown would be rare and a static configuration problem
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
                //return false;
            }
            if (hash == code) {
                return true;
            }
        }
        // The validation code is invalid.
        return false;
    }
    
    private static int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {
        byte[] data = new byte[8];
        long value = t;
        for (int i = 8; i-- > 0; value >>>= 8) {
            data[i] = (byte) value;
        }
        SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signKey);
        byte[] hash = mac.doFinal(data);
        int offset = hash[20 - 1] & 0xF;
        // We're using a long because Java hasn't got unsigned int.
        long truncatedHash = 0;
        for (int i = 0; i < 4; ++i) {
            truncatedHash <<= 8;
            // We are dealing with signed bytes:
            // we just keep the first byte.
            truncatedHash |= (hash[offset + i] & 0xFF);
        }
        truncatedHash &= 0x7FFFFFFF;
        truncatedHash %= 1000000;
        return (int) truncatedHash;
    }
}





工程源码分享:
链接: http://pan.baidu.com/s/1eRUelqi 密码: xz25

<think>我们被要求用Java实现Google Authenticator的TOTP(基于时间的一次性密码)功能。根据引用[3],我们可以参考RFC6238(TOTP)和RFC4226(HOTP)。GoogleAuthenticator使用的是TOTP算法,它是基于HOTP(基于计数器的一次性密码)的,但将计数器替换为时间戳。实现步骤:1.生成一个共享密钥(Base32编码)。2.根据当前时间和一个时间步长(通常为30秒)计算计数器值。3.使用HMAC-SHA1算法(或其他算法,但默认是SHA1)计算HMAC值。4.动态截取HMAC值得到一个整数。5.将这个整数模10^6(即取最后6位)得到6位数字的一次性密码。注意:密钥是Base32编码的,所以我们需要先解码。我们将分步骤实现:步骤1:生成共享密钥(通常由服务器生成,并在用户注册时提供给用户,以二维码形式展示)步骤2:计算TOTP我们不需要生成二维码,只需要实现TOTP的生成和验证。根据RFC6238,TOTP的计算公式为:TOTP =HOTP(K,T)T= floor((CurrentUnix time- T0)/ TS)其中:T0:起始时间,通常为0(Unixepoch)TS:时间步长,通常为30秒因此,我们需要:1.将Base32编码的密钥解码为字节数组。2.计算T值(当前时间戳除以时间步长,取整数部分)。3.用HOTP算法计算一次性密码。HOTP算法的步骤(RFC4226):1.使用密钥K和计数器C(这里是T)计算HMAC值(默认使用HMAC-SHA1)。2.动态截断(Dynamic Truncation):-取HMAC结果的最后一个字节的低4位,作为偏移量offset。-然后从偏移量offset开始的4个字节(按大端序)组成一个整数,并屏蔽最高位(避免符号问题),得到一个无符号整数。3.将这个整数模10^Digit(Digit一般为6)得到6位数字。我们将实现两个主要方法:-generateTOTP(secretKey, time):生成给定时间点的TOTP-validateTOTP(secretKey,code, time,timeStep,window):验证一个TOTP码,允许一个时间窗口(比如前后1个时间步长)注意:时间窗口通常用于处理时间同步问题。由于我们使用Java,可以使用javax.crypto包中的Mac类来计算HMAC-SHA1。另外,Base32解码可以使用ApacheCommons Codec库,但为了减少依赖,我们也可以自己实现一个简单的Base32解码(或者使用Java8的java.util.Base64?注意Base32不是Base64)。不过,Java标准库中没有Base32,因此我们可能需要自己实现或使用第三方库。但为了简洁,这里我们使用Apache CommonsCodec的Base32类(在回答中,如果用户没有该库,我们可以提供一种简单的Base32解码方法,但注意Base32解码相对复杂,且GoogleAuthenticator的Base32是去掉填充的,字母大写)。然而,由于问题要求自包含,我们可以自己写一个简单的Base32解码(仅支持大写字母,无填充)。但为了准确性和时间,我们假设使用Apache CommonsCodec,并在代码中注明。如果用户不想使用第三方库,我们可以提供替代方案。但考虑到问题要求,我们在这里使用纯Java实现Base32解码(参考RFC4648)。由于Base32解码代码较长,我们可以简化:仅处理大写字母,且不考虑填充。另一种选择:在真实项目中,建议使用ApacheCommons Codec的Base32类。但为了示例的独立性,我们将自己实现一个简单的Base32解码(仅支持标准字母表,无填充)。由于时间关系,我们采用一个简化的Base32解码方法(注意:如果密钥有填充,需要先去除等号,但GoogleAuthenticator生成的密钥通常不带填充)。步骤:1.Base32解码:将Base32字符串转换为字节数组。2.计算时间步长计数器T。3.使用HMAC-SHA1计算哈希。4.动态截断得到整数。5.取模得到6位数字。我们开始编写代码。注意:我们使用当前系统时间,时间步长默认为30秒。我们将创建两个类:GoogleAuthenticator和一个测试类。由于代码较长,我们分步骤写。首先,我们实现一个Base32解码的工具方法(仅支持大写,无填充):</think>### Java实现Google Authenticator TOTP功能 以下是完整的Java实现方案,包含TOTP生成和验证的核心逻辑,基于RFC 6238标准[^3]: #### 1. 核心实现类 ```java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.lang.reflect.UndeclaredThrowableException; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.time.Instant; import java.util.Base64; public class GoogleAuthenticator { private static final int TIME_STEP = 30; // 时间步长(秒) private static final int CODE_DIGITS = 6; // 验证码位数 private static final String HMAC_ALGORITHM = "HmacSHA1"; // 哈希算法 /** * 生成TOTP验证码 * @param secretKey Base32编码的密钥 * @return 6位数字验证码 */ public static String generateCode(String secretKey) { // 将Base32密钥解码为字节数组 byte[] key = decodeBase32(secretKey); // 计算当前时间步长计数器 long counter = Instant.now().getEpochSecond() / TIME_STEP; return generateTOTP(key, counter, CODE_DIGITS); } /** * 验证TOTP验证码 * @param secretKey Base32编码的密钥 * @param code 用户输入的验证码 * @param window 允许的时间窗口(步长单位) * @return 验证结果 */ public static boolean verifyCode(String secretKey, String code, int window) { byte[] key = decodeBase32(secretKey); long counter = Instant.now().getEpochSecond() / TIME_STEP; for (int i = -window; i <= window; i++) { String testCode = generateTOTP(key, counter + i, CODE_DIGITS); if (testCode.equals(code)) { return true; } } return false; } private static String generateTOTP(byte[] key, long counter, int codeDigits) { // 将计数器转为字节数组(大端序) byte[] counterBytes = ByteBuffer.allocate(8).putLong(counter).array(); try { // 计算HMAC-SHA1 Mac hmac = Mac.getInstance(HMAC_ALGORITHM); hmac.init(new SecretKeySpec(key, HMAC_ALGORITHM)); byte[] hash = hmac.doFinal(counterBytes); // 动态截断(RFC 4226) int offset = hash[hash.length - 1] & 0xF; int binary = ((hash[offset] & 0x7F) << 24) | ((hash[offset + 1] & 0xFF) << 16) | ((hash[offset + 2] & 0xFF) << 8) | (hash[offset + 3] & 0xFF); // 生成指定位数数字 int otp = binary % (int) Math.pow(10, codeDigits); return String.format("%0" + codeDigits + "d", otp); } catch (GeneralSecurityException e) { throw new UndeclaredThrowableException(e); } } private static byte[] decodeBase32(String base32) { String base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; StringBuilder bits = new StringBuilder(); // 将Base32转为二进制串 for (char c : base32.toUpperCase().toCharArray()) { int val = base32Chars.indexOf(c); if (val >= 0) { bits.append(String.format("%5s", Integer.toBinaryString(val)).replace(' ', '0')); } } // 二进制转字节数组 byte[] bytes = new byte[bits.length() / 8]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) Integer.parseInt(bits.substring(i * 8, (i + 1) * 8), 2); } return bytes; } } ``` #### 2. 使用示例 ```java public class Main { public static void main(String[] args) { // 生成密钥(需Base32编码) String secretKey = "JBSWY3DPEHPK3PXP"; // 生成并验证TOTP String code = GoogleAuthenticator.generateCode(secretKey); System.out.println("生成验证码: " + code); boolean isValid = GoogleAuthenticator.verifyCode(secretKey, code, 1); System.out.println("验证结果: " + isValid); } } ``` #### 3. 关键实现说明 1. **TOTP算法原理**: - 基于时间窗口计算计数器:$T = \lfloor \frac{当前时间戳}{时间步长} \rfloor$ - 使用HMAC-SHA1计算哈希:$HMAC(K, T)$[^3] - 动态截断技术(RFC 4226)生成数字 2. **密钥处理**: - Google Authenticator使用Base32编码密钥[^1] - `decodeBase32()`方法实现自定义解码(避免第三方依赖) 3. **时间窗口验证**: - 允许±1个时间步长的容差(约±30秒) - 解决设备与服务器时间不同步问题 4. **安全性要点**: - 密钥必须安全存储(建议加密) - 生产环境应限制重试次数 - 使用HTTPS传输验证码 #### 4. 集成建议 1. **用户注册流程**: ```java // 生成新密钥 byte[] keyBytes = new byte[20]; new SecureRandom().nextBytes(keyBytes); String secretKey = Base32.getEncoder().encodeToString(keyBytes); // 生成二维码URL(Google格式) String qrUrl = "otpauth://totp/YourApp:user@example.com?secret=" + secretKey; ``` 2. **验证流程**: ```java public boolean authenticate(String username, String code) { String storedKey = getUserSecret(username); // 从数据库获取密钥 return GoogleAuthenticator.verifyCode(storedKey, code, 1); } ``` #### 5. 注意事项 1. 时间同步:服务器需使用NTP保持时间准确 2. 密钥备份:提供恢复码机制 3. 算法扩展:支持HMAC-SHA256/SHA512(需修改`HMAC_ALGORITHM`) 4. 依赖项:仅需标准Java库(Java 8+) 此实现符合RFC 6238标准,可与官方Google Authenticator应用兼容[^1][^3]。实际部署时应添加异常处理和日志监控。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值