package com.czg.third.wechat;

import javax.crypto.AEADBadTagException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 微信参数 AES 解密
 * @author GYJoker
 */
public class WechatAesUtil {
    static final int KEY_LENGTH_BYTE = 32;
    static final int TAG_LENGTH_BIT = 128;
    private final byte[] aesKey;
    public WechatAesUtil(byte[] key) {
        if (key.length != KEY_LENGTH_BYTE) {
            throw new IllegalArgumentException("无效的ApiV3Key，长度必须为32个字节");
        }
        this.aesKey = key;
    }
    public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
            throws GeneralSecurityException {
        try {

            // 调试信息：打印参数信息
            System.out.println("associatedData长度: " + (associatedData != null ? associatedData.length : 0));
            System.out.println("nonce长度: " + (nonce != null ? nonce.length : 0));
            System.out.println("ciphertext长度: " + ciphertext.length());

            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            SecretKeySpec key = new SecretKeySpec(aesKey, "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
            cipher.init(Cipher.DECRYPT_MODE, key, spec);

            // 处理 associatedData，确保使用空数组而非 null
            cipher.updateAAD(associatedData != null ? associatedData : new byte[0]);

            byte[] decodedCiphertext = Base64.getDecoder().decode(ciphertext);
            System.out.println("解码后密文长度: " + decodedCiphertext.length);

            byte[] plaintext = cipher.doFinal(decodedCiphertext);
            return new String(plaintext, StandardCharsets.UTF_8);
        } catch (AEADBadTagException e) {
            // 捕获标签不匹配异常，提供更详细的错误信息
            throw new GeneralSecurityException("解密失败: 标签不匹配，可能是密钥错误、数据被篡改或参数不匹配", e);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException("无效的密钥或参数", e);
        }
    }
}
