google authenticator 工作原理

本文介绍了Google Authenticator的工作原理,它基于TOTP算法实现一次性密码。内容包括HMACSHA1计算签名、生成数字码的流程,以及如何保证时间容错性。详细解析了算法中的时间同步和代码生成步骤,有助于理解双因素身份验证机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Google authenticator

介绍

Google authenticator是一个基于TOTP原理实现的一个生成一次性密码的工具,用来做双因素登录,市面上已经有很多这些比较成熟的东西存在,像是一些经常用到的U盾,以及数字密码等

参考文档

https://tools.ietf.org/html/rfc6238
https://tools.ietf.org/html/rfc4226

实现源码 Google authenticator版本

https://github.com/google/google-authenticator-android

先来看看google-authenticator-android里面实现的一个版本,基于TOTP:Time-based One-time Password Algorithm(基于时间的一次性密码算法)

1.拿到HMACSHA1计算之后的签名

static Signer getSigningOracle(String secret) {
    try {
      //拿到secret base32之后的byte数组
      byte[] keyBytes = decodeKey(secret);
      //使用hmacsha1计算字符串的签名
      final Mac mac = Mac.getInstance("HMACSHA1");
      mac.init(new SecretKeySpec(keyBytes, ""));

      // Create a signer object out of the standard Java MAC implementation.
      return new Signer() {
        @Override
        public byte[] sign(byte[] data) {
          return mac.doFinal(data);
        }
      };
    } catch (DecodingException error) {
     ....
    }

    return null;
  }
 private static byte[] decodeKey(String secret) throws DecodingException {
    return Base32String.decode(secret);
  }

2.生成数字码


public String generateResponseCode(long state)
      throws GeneralSecurityE
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值