package com.kmall.common.utils.wechat.wxglobal;


import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;


import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author huangyq
 * @version 1.0
 * 2018-12-26 14:43
 */
public class RSAUtils {
    protected final Logger logger = LoggerFactory.getLogger(RSAUtils.class);
    private static final String KEY_ALGORITHM = "PKCS12";
    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
    private static final String CIPHER_TYPE = "X.509";
    private static final String ENCRYPT_TYPE = "RSA";


    private PublicKey publicKey;
    private PrivateKey privateKey;
    //初始化证书
    public void initCert(String priKeyPath, String alias, String password, String pubKeyPath) {
        try {
            logger.info("证书初始化开始！");
            KeyStore keystore = KeyStore.getInstance(KEY_ALGORITHM);
            keystore.load(new FileInputStream(new File(priKeyPath)), password.toCharArray());
            privateKey = (PrivateKey) keystore.getKey(alias, password.toCharArray());


            CertificateFactory certificateFactory = CertificateFactory.getInstance(CIPHER_TYPE);
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(new File(pubKeyPath)));
            publicKey = cert.getPublicKey();
            logger.info("证书初始化结束！");
        } catch (Exception e) {
            logger.error("证书初始化异常！{}{}", e.getMessage(), e);
        }
    }

    //签名
    public String signater(String xml) {
        try {
            Signature signature = Signature.getInstance(ENCRYPT_TYPE);
            signature.initSign(privateKey);
            signature.update(xml.getBytes("UTF-8"));
            byte[] result = signature.sign();
            return new String(Base64.encodeBase64String(result));
        } catch (Exception e) {
            logger.error("签名异常！{}{}", e.getMessage(), e);
        }
        return "";
    }

    //验签
    public boolean verify(String xml, String signStr) {
        try {
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(publicKey);
            signature.update(xml.getBytes());
            return signature.verify(Base64.decodeBase64(signStr));
        } catch (Exception e) {
            logger.error("验签异常！{}{}", e.getMessage(), e);
        }
        return false;
    }
}
