Java 读取Cer证书信息

2021-05-10  本文已影响0人  久伴我还是酒伴我
package com.kingxunlian.tax.utils.bcprov.detail;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.BCUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.X500NameBuilder;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.ECGenParameterSpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author leijie.gao
 * @version 1.0.0
 * @ClassName Test1.java
 * @Description TODO
 * @createTime 2021年04月08日 14:02:00
 */
@Slf4j
public class CERUtil {
/**
     * CER证书读取内容并文本存储到数据库
     */
    public static void readCertificate(){
        try{
            Security.addProvider(new BouncyCastleProvider());
            CertificateFactory cf = CertificateFactory.getInstance("X.509","BC");
            X509Certificate cert =(X509Certificate) cf.generateCertificate(new FileInputStream("d:/测试签名.cer"));
            log.info("明文信息:{}",cert.toString());
            log.info("证书信息:{}",Base64.encode(cert.getEncoded()));
            PublicKey publicKey = cert.getPublicKey();
            ECPoint ecPoint = BCUtil.toParams(publicKey).getQ();
            String publicKeyStr = Base64.encode(ecPoint.getEncoded(false));
            log.info("公钥Base64字符串:{}",publicKeyStr);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 证书文本信息读取并转换为证书对象
     */
    public static Map<String,String> writeCertificate(String content){
        Map<String,String> map = new HashMap<>();
        try{
            Security.addProvider(new BouncyCastleProvider());
            CertificateFactory cf = CertificateFactory.getInstance("X.509","BC");
            byte[] re = Base64.decode(content);
            ByteArrayInputStream bain = new ByteArrayInputStream(re);
            X509Certificate cert =(X509Certificate) cf.generateCertificate(bain);
            String certName = cert.getSubjectDN().getName();
            String substring = certName.split(",")[1].split("=")[1]+"【"+certName.substring(certName.lastIndexOf("=")+1)+"】";
            map.put("certName",substring);
            System.out.println(cert.getSubjectDN().getName());
            PublicKey publicKey = cert.getPublicKey();
            log.info("明文信息:{}",cert.toString());
            ECPoint ecPoint = BCUtil.toParams(publicKey).getQ();
            String publicKeyStr = Base64.encode(ecPoint.getEncoded(false));
            map.put("publicKey",publicKeyStr);
            log.info("公钥Base64字符串:{}",publicKeyStr);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 生成PKCS10
     */
    public static void createPkcs10(){
        try{
            Security.addProvider(new BouncyCastleProvider());
            final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
            KeyPairGenerator localKeyPairGenerator = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
            localKeyPairGenerator.initialize(sm2Spec);
            KeyPair localKeyPair = localKeyPairGenerator.genKeyPair();

            PrivateKey privateKey = localKeyPair.getPrivate();
            String privateKeyStr = Base64.encode(privateKey.getEncoded());
            log.info("生成PKCS10 私钥Base64:{}",privateKeyStr);

            PublicKey publicKey = localKeyPair.getPublic();
            ECPoint ecPoint = BCUtil.toParams(publicKey).getQ();
            String publicKeyStr = Base64.encode(ecPoint.getEncoded(false));
            log.info("生成PKCS10 公钥Base64:{}",publicKeyStr);
            X500NameBuilder localX500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
            localX500NameBuilder.addRDN(BCStyle.CN, "电子证书签发系统");
            localX500NameBuilder.addRDN(BCStyle.C, "CN");
            localX500NameBuilder.addRDN(BCStyle.O, "中国航天大学");
            localX500NameBuilder.addRDN(BCStyle.L, "beijing");
            localX500NameBuilder.addRDN(BCStyle.ST, "beijing");
            localX500NameBuilder.addRDN(BCStyle.EmailAddress, "gaoleijie@kingxunlian.com");
            X500Name localX500Name = localX500NameBuilder.build();
            JcaPKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(localX500Name, localKeyPair.getPublic());
            JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SM3WITHSM2");// 签名算法
            ContentSigner signer = csBuilder.build(localKeyPair.getPrivate());
            PKCS10CertificationRequest csr = p10Builder.build(signer);// PKCS10的请求
            StringBuilder builder = new StringBuilder("-----BEGIN CERTIFICATE REQUEST-----\n\n");
            builder.append(Base64.encode(csr.getEncoded())).append("\n\n");
            builder.append("-----END CERTIFICATE REQUEST-----");
            log.info("生成PKCS10 文件内容:\n{}",builder);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读