谷歌身份验证器的使用超详细步骤

骑猪看日落 2024-04-01 13:09 266阅读 0赞

谷歌身份验证器Google Authenticator是谷歌推出的一款动态口令工具,解决大家各平台账户遭到恶意攻击的问题,一般在相关的服务平台登陆中除了用正常用户名和密码外,需要再输入一次谷歌认证器生成的动态口令才能验证成功,相当于输入二次密码,以达到账户的高安全性。例如交易所、金融平台、以及一些钱包等项目等等,都会使用谷歌身份验证器Google Authenticator来做二次认证,开启谷歌身份验证之后,登录账户,除了输入用户名和密码,还需要输入谷歌验证器上的动态密码。谷歌验证器上的动态密码,也称为一次性密码,密码按照时间或使用次数不断动态变化(默认 30 秒变更一次)

  • 使用思路
    1、第一次请求,判断未绑定谷歌验证码,那就生成随机base32的秘钥展示到页面,供用户创建账号,或者生成二维码,供用户在手机端使用谷歌验证器扫码创建账号
    2、绑定验证,将手机app谷歌验证器生成的验证码输入到需要登录的平台验证,成功后将秘钥存入数据库;
    3、绑定过后每次请求查询数据库的秘钥生成二维码传出;
    4、取消绑定,清除数据库的数据。
  • 使用步骤
    手机上下载谷歌身份验证器,便于生成验证码
    iPhone手机:在App Store中搜索 Google Authenticator
    安卓手机:复制该链接到浏览器下载,http://d7.xiaotongqq.com/googe.apk
  • 整合java
    1.导入依赖

    1. <dependency>
    2. <groupId>cn.hutool</groupId>
    3. <artifactId>hutool-all</artifactId>
    4. <version>5.8.2</version>
    5. </dependency>
    6. <!--二维码的生成工具类-->
    7. <dependency>
    8. <groupId>com.google.zxing</groupId>
    9. <artifactId>core</artifactId>
    10. <version>3.3.3</version>
    11. </dependency>
    12. <!--谷歌身份验证器-->
    13. <dependency>
    14. <groupId>commons-codec</groupId>
    15. <artifactId>commons-codec</artifactId>
    16. <version>1.12</version>
    17. </dependency>

2.编写谷歌身份验证器工具类

  1. import java.security.InvalidKeyException;
  2. import java.security.NoSuchAlgorithmException;
  3. import java.security.SecureRandom;
  4. import javax.crypto.Mac;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import org.apache.commons.codec.binary.Base32;
  7. import org.apache.commons.codec.binary.Base64;
  8. /**
  9. * @Description: 谷歌身份验证器工具类
  10. */
  11. public class GoogleAuthenticator {
  12. /**
  13. * 生成秘钥的长度
  14. */
  15. public static final int SECRET_SIZE = 10;
  16. public static final String SEED = "g8GjEvTbW5oVSV7avL47357438reyhreyuryetredLDVKs2m0QN7vxRs2im5MDaNCWGmcD2rvcZx";
  17. /**
  18. * 实现随机数算法
  19. */
  20. public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";
  21. /**
  22. * 时间前后偏移量
  23. * 用于防止客户端时间不精确导致生成的TOTP与服务器端的TOTP一直不一致
  24. * 如果为0,当前时间为 10:10:15
  25. * 则表明在 10:10:00-10:10:30 之间生成的TOTP 能校验通过
  26. * 如果为1,则表明在
  27. * 10:09:30-10:10:00
  28. * 10:10:00-10:10:30
  29. * 10:10:30-10:11:00 之间生成的TOTP 能校验通过
  30. * 以此类推
  31. */
  32. int window_size = 10; // default 3 - max 17
  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. * @return secret key
  48. */
  49. public static String generateSecretKey() {
  50. SecureRandom sr = null;
  51. try {
  52. sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);
  53. sr.setSeed(Base64.decodeBase64(SEED.getBytes()));
  54. byte[] buffer = sr.generateSeed(SECRET_SIZE);
  55. Base32 codec = new Base32();
  56. byte[] bEncodedKey = codec.encode(buffer);
  57. return new String(bEncodedKey);
  58. } catch (NoSuchAlgorithmException e) {
  59. // should never occur... configuration error
  60. }
  61. return null;
  62. }
  63. /**
  64. * 生成一个google身份验证器,识别的字符串,只需要把该方法返回值生成二维码扫描就可以了。
  65. * 最后展示的账户名称将会是 label:user
  66. * @param label 标签
  67. * @param user 账号
  68. * @param secret 密钥
  69. * @return
  70. */
  71. public static String getQRBarcode(String label, String user, String secret) {
  72. String format = "otpauth://totp/%s:%s?secret=%s";
  73. return String.format(format, label, user, secret);
  74. }
  75. /**
  76. * 生成一个google身份验证器,识别的字符串,只需要把该方法返回值生成二维码扫描就可以了。
  77. *最后展示的账户名称将会是 user
  78. * @param user 账号
  79. * @param secret 密钥
  80. * @return
  81. */
  82. public static String getQRBarcode(String user, String secret) {
  83. String format = "otpauth://totp/%s?secret=%s";
  84. return String.format(format, user, secret);
  85. }
  86. /**
  87. * 验证code是否合法
  88. * @param secret 秘钥
  89. * @param code 验证码
  90. * @param timeMses 时间戳
  91. * @return true表示正确 false 表示错误
  92. */
  93. public boolean check_code(String secret, long code, long timeMses) {
  94. if(secret == null || "".equals(secret))
  95. {
  96. return false;
  97. }
  98. Base32 codec = new Base32();
  99. byte[] decodedKey = codec.decode(secret);
  100. // convert unix msec time into a 30 second "window"
  101. // this is per the TOTP spec (see the RFC for details)
  102. long t = (timeMses / 1000L) / 30L;
  103. // Window is used to check codes generated in the near past.
  104. // You can use this value to tune how far you're willing to go.
  105. for (int i = -window_size; i <= window_size; ++i) {
  106. long hash;
  107. try {
  108. hash = verify_code(decodedKey, t + i);
  109. } catch (Exception e) {
  110. // Yes, this is bad form - but
  111. // the exceptions thrown would be rare and a static
  112. // configuration problem
  113. e.printStackTrace();
  114. throw new RuntimeException(e.getMessage());
  115. // return false;
  116. }
  117. if (hash == code) {
  118. return true;
  119. }
  120. }
  121. // The validation code is invalid.
  122. return false;
  123. }
  124. /**
  125. * 根据时间偏移量计算
  126. *
  127. * @param key
  128. * @param t
  129. * @return
  130. * @throws NoSuchAlgorithmException
  131. * @throws InvalidKeyException
  132. */
  133. private static int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {
  134. byte[] data = new byte[8];
  135. long value = t;
  136. for (int i = 8; i-- > 0; value >>>= 8) {
  137. data[i] = (byte) value;
  138. }
  139. SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
  140. Mac mac = Mac.getInstance("HmacSHA1");
  141. mac.init(signKey);
  142. byte[] hash = mac.doFinal(data);
  143. int offset = hash[20 - 1] & 0xF;
  144. // We're using a long because Java hasn't got unsigned int.
  145. long truncatedHash = 0;
  146. for (int i = 0; i < 4; ++i) {
  147. truncatedHash <<= 8;
  148. // We are dealing with signed bytes:
  149. // we just keep the first byte.
  150. truncatedHash |= (hash[offset + i] & 0xFF);
  151. }
  152. truncatedHash &= 0x7FFFFFFF;
  153. truncatedHash %= 1000000;
  154. return (int) truncatedHash;
  155. }
  156. }

3.测试生成秘钥

  1. import cn.hutool.core.io.FileUtil;
  2. import cn.hutool.extra.qrcode.QrCodeUtil;
  3. import com.example.vehicleinformationsystem.util.GoogleAuthenticator;
  4. import org.junit.jupiter.api.Test;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. @SpringBootTest
  7. class VehicleInformationSystemApplicationTests {
  8. private static String secretKey = "";
  9. /**
  10. * 生成秘钥
  11. */
  12. @Test
  13. void contextLoads() {
  14. //生成秘钥
  15. secretKey = GoogleAuthenticator.generateSecretKey();
  16. System.out.println("秘钥:"+secretKey);
  17. }
  18. }

结果:

  1. 秘钥:DPSKD2HAZVANIXX7

秘钥使用方式:
注:该秘钥应该提示用户备份,切勿泄露给第三方,仅展示一次
3.1.在手机上下载谷歌身份验证器(下载方式参考上文)
3.2.点击右下角加号
在这里插入图片描述
3.3.点击输入设置秘钥
3.4.输入需要登录的平台用户名,以及刚才的秘钥,选择基于时间,点击添加
在这里插入图片描述
3.5.添加成功后,如下所示
在这里插入图片描述
3.6.将账号的二维码填写到需要登录的平台进行验证
4.测试生成二维码

  1. /**
  2. * 生成二维码
  3. */
  4. @Test
  5. void contextLoads() {
  6. //生成秘钥
  7. secretKey = GoogleAuthenticator.generateSecretKey();
  8. System.out.println("秘钥:"+secretKey);
  9. //生成二维码信息
  10. String QRBarcode = GoogleAuthenticator.getQRBarcode("system_admin",secretKey);
  11. System.out.println("二维码所需要的信息:"+QRBarcode);
  12. //生成二维码 300 表示二维码的大小 D:\img\aa\qrcode.jpg 表示为二维码的生成路径
  13. QrCodeUtil.generate(QRBarcode, 300, 300, FileUtil.file("D:\\img\\aa\\qrcode.jpg"));
  14. }

生成结果:
在这里插入图片描述
使用方式:
4.1.在手机上下载谷歌身份验证器(下载方式参考上文)
4.2.点击右下角加号
4.3.点击扫描二维码
4.4.扫描生成的二维码,即可
5.5.将账号的二维码填写到需要登录的平台进行验证

5.验证码验证
这里就选择刚才生成的秘钥账户,system
在这里插入图片描述

  1. //刚才生成的秘钥
  2. private static String secretKey = "DPSKD2HAZVANIXX7";
  3. /**
  4. * 测试验证码
  5. */
  6. @Test
  7. void testData() {
  8. String code = "126128";
  9. long time = System.currentTimeMillis ();
  10. GoogleAuthenticator g = new GoogleAuthenticator ();
  11. boolean result = g.check_code (secretKey,Long.valueOf(code),time );
  12. System.out.println ( "验证码是否正确--》"+result );
  13. }

输出结果:

  1. 验证码是否正确--》true

发表评论

表情:
评论列表 (有 0 条评论,266人围观)

还没有评论,来说两句吧...

相关阅读