package com.eactive.eai.authserver.jwt;

import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;

import org.springframework.security.jwt.crypto.sign.InvalidSignatureException;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;

/**
 * PS256 (RSA-PSS + SHA-256) 서명 검증 구현체.
 * RFC 7518 §3.5 파라미터: Hash=SHA-256, MGF=MGF1/SHA-256, saltLen=32, trailer=0xBC
 */
public class RsaPssVerifier implements SignatureVerifier {

    private static final PSSParameterSpec PSS_SPEC =
            new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1);

    private final RSAPublicKey publicKey;

    public RsaPssVerifier(RSAPublicKey publicKey) {
        this.publicKey = publicKey;
    }

    @Override
    public void verify(byte[] content, byte[] signature) {
        try {
            Signature sig = Signature.getInstance("RSASSA-PSS");
            sig.setParameter(PSS_SPEC);
            sig.initVerify(publicKey);
            sig.update(content);
            if (!sig.verify(signature)) {
                throw new InvalidSignatureException("RSA-PSS 서명 검증 실패");
            }
        } catch (InvalidSignatureException e) {
            throw e;
        } catch (Exception e) {
            throw new InvalidSignatureException("RSA-PSS 서명 검증 실패: " + e.getMessage());
        }
    }

    @Override
    public String algorithm() {
        return "PS256";
    }
}
