如何在Java处理PFX格式证书

公钥加密技术12号标准(Public Key Cryptography Standards #12,PKCS#12)为存储和传输用户或服务器私钥、公钥和证书指定了一个可移植的格式。它是一种二进制格式,这些文件也称为PFX文件。

如何在Java处理PFX格式证书

开发人员通常需要将PFX文件转换为某些不同的格式,如PEM或JKS,以便可以为使用SSL通信的独立Java客户端或WebLogic Server使用

在Security编程中,有几种典型的密码交换信息文件格式:

DER-encoded certificate: ,

PEM-encoded message:

PKCS#12 Personal Information Exchange: , .p12

PKCS#10 Certification Request: .p10

PKCS#7 cert request response: .p7r

PKCS#7 binary message: .p7b

是用于存放证书,它是2进制形式存放的,不含私钥。

跟crt/cer的区别是它以Ascii来表示。

pfx/p12用于存放个人证书/私钥,他通常包含保护密码,2进制方式

p10是证书请求

p7r是CA对证书请求的回复,只用于导入

p7b以树状展示证书链(certificate chain),同时也支持单个证书,不含私钥。

其中,我介绍如何从p12/pfx文件中提取密钥对及其长度:

1,首先,读取pfx/p12文件(需要提供保护密码)

2,通过别名(Alias,注意,所有证书中的信息项都是通过Alias来提取的.)提取你想要分析的证书链

3,再将其转换为一个以X509证书结构体

4,提取里面的项,如果那你的证书项放在第一位(单一证书),直接读取 x509Certs[0](见下面的代码)这个X509Certificate对象

5,X509Certificate对象有很多方法,tain198127网友希望读取RSA密钥(公私钥)及其长度(见),那真是太Easy了,

X509Certificate keyPairCert = x509Certs[0];

int iKeySize = ertificateKeyLength(keyPairCert);

tln("证书密钥算法="+ublicKey()lgorithm());

tln("证书密钥长度="+iKeySize);

提取了他所需要的信息。

package air;

import ;

import InputStream;

import NotFoundException;

import ception;

import tore;

import toreException;

import chAlgorithmException;

import chProviderException;

import rity;

import ificate;

import ificateException;

import .X509Certificate;

import ool.X509CertUtil;

public class LoadKeyFromPKCS12 {

public static void main(String[] args) {

try {

// Open an input stream on the keystore file

String pfxFileName = " c: " ;

String pfxPassword = " 123456 " ;

File fPkcs12 = null ;

if (pfxFileName != null ) {

// Open the file

fPkcs12 = new File(pfxFileName);

}

FileInputStream fis = new FileInputStream(fPkcs12);

// Create a keystore object

KeyStore keyStore = null ;

try

{

// Need BC provider for PKCS #12, BKS and UBER

if (rovider( " BC " ) == null )

{

throw new Exception( " 不能Load入BouncyCastle! " );

}

keyStore = nstance( " PKCS12 " , " BC " );

}

catch (KeyStoreException ex)

{

throw new Exception( " 不能正确解释pfx文件! " );

}

catch (NoSuchProviderException ex)

{

throw new Exception( " Security Provider配置有误! " );

}

try

{

// Load the file into the keystore

(fis, arArray());

}

catch (CertificateException ex)

{

throw new Exception( " 证书格式问题! " );

}

catch (NoSuchAlgorithmException ex)

{

throw new Exception( " 算法不支持! " );

}

catch (FileNotFoundException ex)

{

throw new Exception( " pfx文件没找到 " );

}

catch (IOException ex)

{

throw new Exception( " 读取pfx有误! " );

}

// 获取我的证书链的中keyEntry的别名

Certificate[] certs = ertificateChain( " ng " );

X509Certificate[] x509Certs = ertCertificates(certs);

if (x509Certs == null )

{

return ;

}

x509Certs = rX509CertChain(x509Certs);

X509Certificate keyPairCert = x509Certs[ 0 ];

int iKeySize = ertificateKeyLength(keyPairCert);

tln( " 证书密钥算法= " + ublicKey()lgorithm());

tln( " 证书密钥长度= " + iKeySize);

} catch (Exception e) {

tStackTrace();

}

}

}