添加登入添加Google Authenticator TOTP六位动态码 授权登。2. 保留Google登录并支持动态码登录

This commit is contained in:
lu7213 committed 2026-10-21 04:03:06 -04:00
1 parent 42a06f7e4d
commit cc5fe279e9
13 files changed
+714 -2

No files matched your search

@@ -0,0 +1,87 @@
package com.ruoyi.common.utils;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Locale;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/** Google Authenticator 兼容的 RFC 6238:SHA-1、30 秒、6 位数字。 */
public final class TotpUtils {
private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
private static final SecureRandom RANDOM = new SecureRandom();
private TotpUtils() { }
/** 160 位随机密钥,Base32 无填充编码,不能写日志。 */
public static String newSecret() {
byte[] bytes = new byte[20];
RANDOM.nextBytes(bytes);
StringBuilder value = new StringBuilder(32);
int buffer = 0;
int bits = 0;
for (byte item : bytes) {
buffer = (buffer << 8) | (item & 255);
bits += 8;
while (bits >= 5) {
bits -= 5;
value.append(BASE32.charAt((buffer >> bits) & 31));
}
}
return value.toString();
}
/** 返回命中的时间步;允许前后各 30 秒时钟误差,失败返回 -1。 */
public static long matchingStep(String secret, String code, long epochSeconds) {
if (code == null || !code.matches("[0-9]{6}")) {
return -1;
}
long current = epochSeconds / 30;
// 优先当前步,保留六位码的前导零;时间步消费由数据库原子完成。
for (int offset : new int[] {0, -1, 1}) {
long step = current + offset;
if (step >= 0 && MessageDigest.isEqual(generate(secret, step).getBytes(StandardCharsets.US_ASCII),
code.getBytes(StandardCharsets.US_ASCII))) {
return step;
}
}
return -1;
}
public static String generate(String secret, long step) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(decode(secret), "HmacSHA1"));
byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(step).array());
int offset = hash[hash.length - 1] & 15;
int number = ((hash[offset] & 127) << 24) | ((hash[offset + 1] & 255) << 16)
| ((hash[offset + 2] & 255) << 8) | (hash[offset + 3] & 255);
return String.format(Locale.ROOT, "%06d", number % 1000000);
} catch (GeneralSecurityException exception) {
throw new IllegalStateException("动态码算法不可用");
}
}
private static byte[] decode(String value) {
byte[] result = new byte[value.length() * 5 / 8];
int buffer = 0;
int bits = 0;
int index = 0;
for (char character : value.toCharArray()) {
int digit = BASE32.indexOf(character);
if (digit < 0) {
throw new IllegalArgumentException("动态码密钥格式无效");
}
buffer = (buffer << 5) | digit;
bits += 5;
if (bits >= 8) {
bits -= 8;
result[index++] = (byte) (buffer >> bits);
}
}
return result;
}
}