//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.tmerclub.cloud.payment.allinpay.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
/**
 * @author lanhai
 */
public class Sm2Utils {
    private static final Provider PROVIDER = new BouncyCastleProvider();
    private static final Logger logger = LoggerFactory.getLogger(Sm2Utils.class);

    public static String sign(PrivateKey privateKey, String text) throws Exception {
        Signature signature = Signature.getInstance("SM3withSm2", PROVIDER);
        signature.initSign(privateKey);
        byte[] plainText = text.getBytes(StandardCharsets.UTF_8);
        signature.update(plainText);
        byte[] signatureValue = signature.sign();
        return Base64.encode(signatureValue);
    }

    public static PublicKey loadPublicKey(String certPath) throws Exception {
        PublicKey pubKey;
        X509Certificate x509Certificate;
        Security.addProvider(PROVIDER);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
        FileInputStream fileInputStream = new FileInputStream(certPath);
        x509Certificate = (X509Certificate) certificateFactory.generateCertificate(fileInputStream);
        fileInputStream.close();
        pubKey = x509Certificate.getPublicKey();
        return pubKey;
    }

    public static PrivateKey loadPrivateKey(String certPath, String password) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        FileInputStream is = new FileInputStream(certPath);
        ks.load(is, password.toCharArray());
        is.close();
        Enumeration<String> aliases = ks.aliases();
        String keyAlias = null;
        if (aliases.hasMoreElements()) {
            keyAlias = aliases.nextElement();
        }

        return (PrivateKey) ks.getKey(keyAlias, password.toCharArray());
    }

    public static boolean verify(PublicKey publicKey, String text, String sign) throws Exception {
        if (OpenUtils.isEmpty(sign)) {
            return false;
        } else {
            Signature signature = Signature.getInstance("SM3withSm2", PROVIDER);
            signature.initVerify(publicKey);
            signature.update(text.getBytes(StandardCharsets.UTF_8));
            byte[] signed = Base64.decode(sign);
            return signature.verify(signed);
        }
    }
}
