登录遇到Google认证怎么办?
TOTP是什么?(Google Authenticator)
TOTP(Time-based One-Time Password)是一种基于时间的一次性密码算法,主要用于双因素身份验证。其核心原理是通过共享密钥和时间同步生成动态密码,具体步骤如下:
-
共享密钥:服务端与客户端预先共享一个密钥(通常为Base32编码的字符串)。
-
时间分片:将当前时间戳(Unix时间,秒级)除以固定时间窗口(如30秒),得到一个整数时间计数器(
T
)。 -
HMAC哈希:用密钥对时间计数器
T
进行HMAC-SHA1运算,生成20字节的哈希值。 -
动态截断:
- 取哈希值末4位的低4位作为偏移量
offset
。 - 从
offset
位置截取4字节数据,转换为31位整数S
。
- 取哈希值末4位的低4位作为偏移量
-
生成OTP:对
S
取模运算(如S % 10^6
),生成6-8位的数字密码,有效期为一个时间窗口。
特点:
- 密码每30秒(可配置)自动更新,防止重放攻击。
- 依赖时间同步,通常允许±1个时间窗口的容差。
- 无需联网通信,离线设备(如验证器App)亦可生成有效密码。
TOTP广泛用于Google Authenticator、Microsoft Authenticator等双因素认证工具,平衡安全性与用户体验。
以下是代码实现,已将二维码提取为URI如代码所示
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base32;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;public class TOTPGenerator {public static void main(String[] args) throws Exception {// 二维码提取URI<