XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEServerManager

【Java】我的世界XFE服务器管理器

公开
关注 0 Fork 0 Star 0
UTF-8
package com.xfestudio.xfeservermanager.infra.security;

import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.time.Clock;
import java.time.Instant;
import java.util.Locale;
import java.util.OptionalLong;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/** RFC 6238 compatible SHA-1 TOTP validator with one step of clock skew. */
public final class TotpService {
    private static final long STEP_SECONDS = 30;
    private static final char[] BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".toCharArray();
    private final Clock clock;

    public TotpService(Clock clock) {
        this.clock = clock;
    }

    public boolean verify(byte[] secret, String suppliedCode) {
        return matchingCounter(secret, suppliedCode).isPresent();
    }

    /**
     * Returns the accepted moving counter so callers can reject replay of a code inside its
     * thirty-second window. The counter, rather than the six-digit code, is persisted.
     */
    public OptionalLong matchingCounter(byte[] secret, String suppliedCode) {
        if (secret == null || secret.length < 16 || suppliedCode == null
                || !suppliedCode.matches("[0-9]{6}")) {
            return OptionalLong.empty();
        }
        long counter = Instant.now(clock).getEpochSecond() / STEP_SECONDS;
        int supplied = Integer.parseInt(suppliedCode);
        for (long candidate = counter - 1; candidate <= counter + 1; candidate++) {
            if (constantTimeInt(supplied, generate(secret, candidate))) {
                return OptionalLong.of(candidate);
            }
        }
        return OptionalLong.empty();
    }

    public int currentCode(byte[] secret) {
        return generate(secret, Instant.now(clock).getEpochSecond() / STEP_SECONDS);
    }

    public String formatCode(int code) {
        return String.format(Locale.ROOT, "%06d", code);
    }

    /** RFC 4648 Base32 without padding, suitable for an otpauth enrollment URI. */
    public String base32Secret(byte[] secret) {
        if (secret == null || secret.length < 16) {
            throw new IllegalArgumentException("TOTP secret must contain at least 128 bits");
        }
        StringBuilder encoded = new StringBuilder((secret.length * 8 + 4) / 5);
        int buffer = 0;
        int bits = 0;
        for (byte value : secret) {
            buffer = (buffer << 8) | (value & 0xff);
            bits += 8;
            while (bits >= 5) {
                encoded.append(BASE32[(buffer >>> (bits - 5)) & 0x1f]);
                bits -= 5;
            }
        }
        if (bits > 0) {
            encoded.append(BASE32[(buffer << (5 - bits)) & 0x1f]);
        }
        return encoded.toString();
    }

    private static int generate(byte[] secret, long counter) {
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(new SecretKeySpec(secret, "HmacSHA1"));
            byte[] digest = mac.doFinal(ByteBuffer.allocate(Long.BYTES).putLong(counter).array());
            int offset = digest[digest.length - 1] & 0x0f;
            int binary = ((digest[offset] & 0x7f) << 24)
                    | ((digest[offset + 1] & 0xff) << 16)
                    | ((digest[offset + 2] & 0xff) << 8)
                    | (digest[offset + 3] & 0xff);
            return binary % 1_000_000;
        } catch (GeneralSecurityException impossible) {
            throw new IllegalStateException("HmacSHA1 is unavailable", impossible);
        }
    }

    private static boolean constantTimeInt(int left, int right) {
        int value = left ^ right;
        value |= -value;
        return (value >>> 31) == 0;
    }
}