什么是p7b格式证书?
p7b一般是证书链,里面包括1到多个证书,至少包含一个根证书。
我们项目中利用第三方证书颁发机构进行证书的获取以及管理,最近遇到需要将base64后的p7b格式证书调用链进行解析后将证书信息入库,留作后期数据核对结算,在网上找了解析p7b的例子无果后,特地记录在此供需要者参考。
java 解析p7b
public static X509Certificatepkcs7CertificateOfAnalysis(String buffer)throws Exception {
// 文件格式
/*File f = new File("C:\\Users\\W\\Desktop\\public_key.p7b");
byte[] buffer = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();*/
PKCS7 pkcs7 =new PKCS7(Base64.decode(buffer));
X509Certificate[] certificates = pkcs7.getCertificates();
if(certificates ==null){
throw new ApiException(WrapperEnumError.SIGN_AUTHENTICATION.getCode(),"The certificate is empty");
}
List x509Certificates =new ArrayList(Arrays.asList(certificates));
int length = x509Certificates.size();
String rootSub =null;
//证书调用链必有一个根证书
for (int i =0; i < length; i++) {
X509Certificate certificate = x509Certificates.get(i);
//判断根证书
if(certificate.getSubjectDN().getName().equals(certificate.getIssuerDN().getName())){
rootSub = certificate.getSubjectDN().getName();
x509Certificates.remove(i);
length = length -1;
}
}
//判断二级ca证书
for (int i =0; i < length; i++) {
X509Certificate certificate = x509Certificates.get(i);
if(certificate.getIssuerDN().getName().equals(rootSub)){
x509Certificates.remove(i);
length = length -1;
}
}
//由于我们对接的第三方 第三方根证 --> 第三方为公司颁发的ca根证 --> 用户证书
X509Certificate certificate = x509Certificates.get(x509Certificates.size() -1);
// certificate.verify(certificate.getPublicKey());
return certificate;
}
网友评论