java 解析p12证书 (获取公钥、私钥、序列号)

          

1. p12文件放在resources目录下

java 解析p12证书 (获取公钥、私钥、序列号)_第1张图片

 
  
2. P12InfoVo

import lombok.Builder;
import lombok.Data;

import java.io.Serializable;
import java.security.PrivateKey;
import java.security.PublicKey;


/**
 * p12证书VO
 */
@Data
@Builder
public class P12InfoVo implements Serializable{

    /**
     * 证书公钥
     */
    private final PublicKey publicKey;

    /**
     * 证书私钥
     */
    private final PrivateKey privateKey;

    /**
     * 证书序列号
     */
    private final String serialNo;
}

3. P12Utils

import com.ruoyi.ruoyils.utils.WxPayUtils;
import org.junit.Test;
import sun.security.x509.X509CertImpl;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Enumeration;


/**
 *
 * PKCS12证书中解析公钥、私钥、证书序列号
 *
 * apiclient_cert.p12
 *
 */
public class P12Utils {


    @Test
    public void test(){
        // p12证书路径
        String path = "D:\\Java\\work\\ChenXinCode\\light_show\\ruoyi-admin\\src\\main\\resources\\apiclient_cert.p12";
        P12InfoVo vo = this.parse(path, WxPayUtils.mchId);

        System.out.println("证书公钥: " + vo.getPublicKey());
        System.out.println("证书私钥: " + vo.getPrivateKey());
        System.out.println("证书序列号: " + vo.getSerialNo());
    }

    /**
     * 解析p12文件
     *
     * @param p12Path   证书文件路径
     * @param passwd    证书密码 (也就是商户号)
     * @return
     */
    public static P12InfoVo parse(String p12Path, String passwd) {
        try {
            // 获取文件流
            FileInputStream is = new FileInputStream(p12Path);

            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(is, passwd.toCharArray());
            String keyAlias = null;
            //解析证书,必须有别名
            Enumeration aliases = ks.aliases();
            if (aliases.hasMoreElements()) {
                keyAlias = aliases.nextElement();
            }
            //解析私钥
            PrivateKey privateKey = (PrivateKey) ks.getKey(keyAlias, passwd.toCharArray());
            Certificate cert = ks.getCertificate(keyAlias);
            BigInteger serialNumber = ((X509CertImpl) cert).getSerialNumber();
            //证书一般都使用16进制表示
            String certSn = serialNumber.toString(16).toUpperCase();

            //设置证书公钥、私钥、序列号
            return P12InfoVo.builder()
                    .publicKey(cert.getPublicKey())
                    .privateKey(privateKey)
                    .serialNo(certSn)
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

你可能感兴趣的:(微信小程序,java,微信小程序)