package ink.wgink.module.wechat.utils.pay;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.cert.*;

/**
 * @ClassName: PayCertificateUtil
 * @Description: 证书工具
 * @Author: wanggeng
 * @Date: 2021/8/18 8:38 下午
 * @Version: 1.0
 */
public class PayCertificateUtil {

    /**
     * 获取证书
     *
     * @param inputStream
     * @return
     */
    public static X509Certificate getCertificate(InputStream inputStream) {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
            cert.checkValidity();
            return cert;
        } catch (CertificateExpiredException e) {
            throw new RuntimeException("证书已过期", e);
        } catch (CertificateNotYetValidException e) {
            throw new RuntimeException("证书尚未生效", e);
        } catch (CertificateException e) {
            throw new RuntimeException("无效的证书", e);
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        X509Certificate certificate = PayCertificateUtil.getCertificate(new FileInputStream(new File("/Users/wanggeng/tencent/tenlion/cert/1609461201_20210818_cert/apiclient_cert.pem")));

        System.out.println("输出证书信息:\n" + certificate.toString());
        System.out.println("证书序列号:" + certificate.getSerialNumber().toString(16));
        System.out.println("版本号:" + certificate.getVersion());
        System.out.println("签发者：" + certificate.getIssuerDN());
        System.out.println("有效起始日期：" + certificate.getNotBefore());
        System.out.println("有效终止日期：" + certificate.getNotAfter());
        System.out.println("主体名：" + certificate.getSubjectDN());
        System.out.println("签名算法：" + certificate.getSigAlgName());
        System.out.println("签名：" + certificate.getSignature().toString());
    }

}
