在Security编程中有几种典型的密码交换信息文件格式:
DERencoded certificate: cer crt
PEMencoded message: pem
PKCS# Personal Information Exchange: pfx p
PKCS# Certification Request: p
PKCS# cert request response: pr
PKCS# binary message: pb
cer/crt是用于存放证书它是进制形式存放的不含私钥
pem跟crt/cer的区别是它以Ascii来表示
pfx/p用于存放个人证书/私钥他通常包含保护密码进制方式
p是证书请求
pr是CA对证书请求的回复只用于导入
pb以树状展示证书链(certificate chain)同时也支持单个证书不含私钥
其中我介绍如何从p/pfx文件中提取密钥对及其长度:
首先读取pfx/p文件(需要提供保护密码)
通过别名(Alias注意所有证书中的信息项都是通过Alias来提取的)提取你想要分析的证书链
再将其转换为一个以X证书结构体
提取里面的项如果那你的证书项放在第一位(单一证书)直接读取 xCerts[](见下面的代码)这个XCertificate对象
XCertificate对象有很多方法tain网友希望读取RSA密钥(公私钥)及其长度(见?topicId=&forumId=&)那真是太Easy了
XCertificate keyPairCert = xCerts[];
int iKeySize = XCertUtilgetCertificateKeyLength(keyPairCert);
Systemoutprintln(证书密钥算法=+keyPairCertgetPublicKey()getAlgorithm());
Systemoutprintln(证书密钥长度=+iKeySize);
提取了他所需要的信息
package orgdevdevclientkeypair;
import javaioFile;
import javaioFileInputStream;
import javaioFileNotFoundException;
import javaioIOException;
import javasecurityKeyStore;
import javasecurityKeyStoreException;
import javasecurityNoSuchAlgorithmException;
import javasecurityNoSuchProviderException;
import javasecuritySecurity;
import javasecuritycertCertificate;
import javasecuritycertCertificateException;
import javasecuritycertXCertificate;
import orgdevdevsecuritykeytoolXCertUtil;
public class LoadKeyFromPKCS {
public static void main(String[] args) {
try {
// Open an input stream on the keystore file
String pfxFileName = c:\\davidturingpfx ;
String pfxPassword = ;
File fPkcs = null ;
if (pfxFileName != null ) {
// Open the file
fPkcs = new File(pfxFileName);
}
FileInputStream fis = new FileInputStream(fPkcs);
// Create a keystore object
KeyStore keyStore = null ;
try
{
// Need BC provider for PKCS # BKS and UBER
if (SecuritygetProvider( BC ) == null )
{
throw new Exception( 不能Load入BouncyCastle! );
}
keyStore = KeyStoregetInstance( PKCS BC );
}
catch (KeyStoreException ex)
{
throw new Exception( 不能正确解释pfx文件! );
}
catch (NoSuchProviderException ex)
{
throw new Exception( Security Provider配置有误! );
}
try
{
// Load the file into the keystore
keyStoreload(fis pfxPasswordtoCharArray());
}
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 = keyStoregetCertificateChain( davidturing );
XCertificate[] xCerts = nvertCertificates(certs);
if (xCerts == null )
{
return ;
}
xCerts = XCertUtilorderXCertChain(xCerts);
XCertificate keyPairCert = xCerts[ ];
int iKeySize = XCertUtilgetCertificateKeyLength(keyPairCert);
Systemoutprintln( 证书密钥算法= + keyPairCertgetPublicKey()getAlgorithm());
Systemoutprintln( 证书密钥长度= + iKeySize);
} catch (Exception e) {
eprintStackTrace();
}
}
}