java 从 PKCS12(比如pfx格式)证书中提取私钥证书(PrivateKey)和受信任的公钥证书(X509Certificate)的序列号(SerialNumber)

Posted frankyou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 从 PKCS12(比如pfx格式)证书中提取私钥证书(PrivateKey)和受信任的公钥证书(X509Certificate)的序列号(SerialNumber)相关的知识,希望对你有一定的参考价值。

 

import lombok.Cleanup;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

/**
 * An utility class for obtaining @link PrivateKey and the serial number of the trusted @link X509Certificate 
* from keystore in PKCS12 format
*/ @Getter @Setter @UtilityClass public class SignCertInfo private static final SignCertInfo DEFAULT = new SignCertInfo(); private String certId; private PrivateKey privateKey; public static SignCertInfo createNew(Configs configs) return createNewFrom(getKeyStore(configs), configs); @SneakyThrows private static SignCertInfo createNewFrom(KeyStore store, Configs configs) Enumeration<String> aliases = store.aliases(); while (aliases.hasMoreElements()) String alia = aliases.nextElement(); if (isX509Cert(store, alia)) newSignCertInfo(store, alia, configs); return DEFAULT; @SneakyThrows private static KeyStore getKeyStore(Configs configs) @Cleanup FileInputStream stream = new FileInputStream(configs.getPfxPath()); KeyStore store = KeyStore.getInstance(Pkcs12KeyStore.TYPE, Pkcs12KeyStore.PROVIDER); store.load(stream, configs.getPfxPasswd().toCharArray()); return store; @SneakyThrows private static boolean isX509Cert(KeyStore store, String alia) return CertificateType.X509.equalsIgnoreCase(store.getCertificate(alia).getType()); @SneakyThrows private static SignCertInfo newSignCertInfo(KeyStore store, String alia, Configs configs) SignCertInfo signCertInfo = new SignCertInfo(); signCertInfo.setCertId(((X509Certificate) store.getCertificate(alia)).getSerialNumber().toString()); signCertInfo.setPrivateKey((PrivateKey) store.getKey(alia, configs.getPfxPasswd().toCharArray())); return signCertInfo;

 

public interface Pkcs12KeyStore 

  String TYPE = "PKCS12";

  String PROVIDER = "SunJSSE";

 

以上是关于java 从 PKCS12(比如pfx格式)证书中提取私钥证书(PrivateKey)和受信任的公钥证书(X509Certificate)的序列号(SerialNumber)的主要内容,如果未能解决你的问题,请参考以下文章

pfx是啥文件

pfx格式文件如何打开?如题 谢谢了

openssl将私钥和crt证书合成pfx证书

从 .pfx 文件中提取证书和私钥文件

pfx是啥格式的文件啊

.pfx和.Cer 证书