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.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class SecureTokens {
    private static final SecureRandom RANDOM = new SecureRandom();

    private SecureTokens() {}

    public static String randomUrlToken(int bytes) {
        if (bytes < 16 || bytes > 128) {
            throw new IllegalArgumentException("token entropy must be between 16 and 128 bytes");
        }
        byte[] value = randomBytes(bytes);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(value);
    }

    public static byte[] randomBytes(int bytes) {
        if (bytes < 16 || bytes > 128) {
            throw new IllegalArgumentException("token entropy must be between 16 and 128 bytes");
        }
        byte[] value = new byte[bytes];
        RANDOM.nextBytes(value);
        return value;
    }

    public static byte[] sha256(String token) {
        try {
            return MessageDigest.getInstance("SHA-256")
                    .digest(token.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException impossible) {
            throw new IllegalStateException("SHA-256 is unavailable", impossible);
        }
    }

    public static boolean constantTimeEquals(byte[] left, byte[] right) {
        return MessageDigest.isEqual(left, right);
    }

    /** Stable double-submit token derived from, but not revealing, the raw session token. */
    public static String deriveCsrfToken(String sessionToken) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(
                    sessionToken.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] derived = mac.doFinal("xfesm-csrf-v1".getBytes(StandardCharsets.UTF_8));
            return Base64.getUrlEncoder().withoutPadding().encodeToString(derived);
        } catch (java.security.GeneralSecurityException impossible) {
            throw new IllegalStateException("HmacSHA256 is unavailable", impossible);
        }
    }
}