package cn.anicert.secure.access.utils;

import cn.anicert.module.sign.bc.ICryptoService;
import cn.anicert.module.sign.bc.exception.BadKeyException;
import cn.anicert.module.sign.bc.exception.BadSignatureException;
import cn.anicert.module.sign.bc.mix.MixCryptoFactory;
import cn.anicert.module.sign.bc.std.Asymmetric;
import cn.anicert.module.sign.bc.std.Symmetric;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;

public class SignUtil {
    private final static ICryptoService cryptoService = MixCryptoFactory.getInstance(Asymmetric.SM2, Symmetric.SM4);

    public static String sign(String signBody) throws BadSignatureException, BadKeyException {
        return sign(signBody, ConfigUtil.getConfig().getSignPrivateKey());
    }

    public static String sign(String signBody, String signPriKey) throws BadSignatureException, BadKeyException {
        return Base64.encodeBase64String(cryptoService.sign(signPriKey, signBody.getBytes(StandardCharsets.UTF_8)));
    }

    public static boolean verifySign(String body, String sign) throws BadSignatureException, BadKeyException {
        return verifySign(body, sign, ConfigUtil.getConfig().getSignVerifyPublicKey());
    }

    public static boolean verifySign(String body, String sign, String key) throws BadSignatureException, BadKeyException {
        byte[] byteSign = Base64.decodeBase64(sign);
        byte[] byteBody = body.getBytes(StandardCharsets.UTF_8);
        return cryptoService.verifySign(key, byteSign, byteBody);
    }

}
