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.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;

public final class AesGcmSecretBox {
    private static final SecureRandom RANDOM = new SecureRandom();
    private static final int NONCE_BYTES = 12;
    private static final int TAG_BITS = 128;
    private final SecretKey key;

    public AesGcmSecretBox(SecretKey key) {
        this.key = key;
    }

    public byte[] encrypt(byte[] plaintext, byte[] associatedData) {
        byte[] nonce = new byte[NONCE_BYTES];
        RANDOM.nextBytes(nonce);
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, nonce));
            cipher.updateAAD(associatedData);
            byte[] ciphertext = cipher.doFinal(plaintext);
            return ByteBuffer.allocate(1 + nonce.length + ciphertext.length)
                    .put((byte) 1)
                    .put(nonce)
                    .put(ciphertext)
                    .array();
        } catch (GeneralSecurityException exception) {
            throw new IllegalStateException("secret encryption failed", exception);
        }
    }

    public byte[] decrypt(byte[] encoded, byte[] associatedData) {
        if (encoded == null || encoded.length < 1 + NONCE_BYTES + 16 || encoded[0] != 1) {
            throw new IllegalArgumentException("invalid encrypted secret");
        }
        byte[] nonce = java.util.Arrays.copyOfRange(encoded, 1, 1 + NONCE_BYTES);
        byte[] ciphertext = java.util.Arrays.copyOfRange(encoded, 1 + NONCE_BYTES, encoded.length);
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, nonce));
            cipher.updateAAD(associatedData);
            return cipher.doFinal(ciphertext);
        } catch (GeneralSecurityException exception) {
            throw new IllegalArgumentException("secret authentication failed", exception);
        }
    }
}