目录
一、通过x509Certificate来获取CA证书的基本信息
单独使用x509Certificate只能获取第一步中的基本信息,虽然断点时能看到公钥长度,却不能获取公钥长度,所以这个时候获取到Publickey后就可以使用第二步的方法获取公钥长度。
一、通过x509Certificate来获取CA证书的基本信息
//创建X509工厂类
CertificateFactory cf = CertificateFactory.getInstance("X.509");
//创建证书对象
X509Certificate oCert = (X509Certificate)cf.generateCertificate(inStream);// inStream证书的传入数据
inStream.close();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
String info = null;
//获得证书版本
info = String.valueOf(oCert.getVersion());
System.out.println("证书版本:"+info);
//获得证书序列号
info = oCert.getSerialNumber().toString(16);
System.out.println("证书序列号:"+info);
//获得证书有效期
Date beforedate = oCert.getNotBefore();
info = dateformat.format(beforedate);
System.out.println("证书生效日期:"+info);
Date afterdate = oCert.getNotAfter();
info = dateformat.format(afterdate);
System.out.println("证书失效日期:"+info);
//获得证书主体信息
info = oCert.getSubjectDN().getName();
System.out.println("证书拥有者:"+info);
//获得证书颁发者信息
info = oCert.getIssuerDN().getName();
System.out.println("证书颁发者:"+info);
//获得证书签名算法名称
info = oCert.getSigAlgName();
System.out.println("证书签名算法:"+info);
byte[] byt = oCert.getExtensionValue("1.2.86.11.7.9");
String strExt = new String(byt);
System.out.println("证书扩展域:" + strExt);
byt = oCert.getExtensionValue("1.2.86.11.7.1.8");
String strExt2 = new String(byt);
System.out.println("证书扩展域2:" + strExt2);
二、 通过公钥获取公钥长度
通过X509Certificate.getPublicKey 获取公钥
/**
* Gets the key length of supported keys
* @param pk PublicKey used to derive the keysize
* @return -1 if key is unsupported, otherwise a number >= 0. 0 usually means the length can not be calculated,
* for example if the key is an EC key and the "implicitlyCA" encoding is used.
*/
public static int getKeyLength(final PublicKey pk) {
int len = -1;
if (pk instanceof RSAPublicKey) {
final RSAPublicKey rsapub = (RSAPublicKey) pk;
len = rsapub.getModulus().bitLength();
} else if (pk instanceof JCEECPublicKey) {
final JCEECPublicKey ecpriv = (JCEECPublicKey) pk;
final org.bouncycastle.jce.spec.ECParameterSpec spec = ecpriv.getParameters();
if (spec != null) {
len = spec.getN().bitLength();
} else {
// We support the key, but we don't know the key length
len = 0;
}
} else if (pk instanceof ECPublicKey) {
final ECPublicKey ecpriv = (ECPublicKey) pk;
final java.security.spec.ECParameterSpec spec = ecpriv.getParams();
if (spec != null) {
len = spec.getOrder().bitLength(); // does this really return something we expect?
} else {
// We support the key, but we don't know the key length
len = 0;
}
} else if (pk instanceof DSAPublicKey) {
final DSAPublicKey dsapub = (DSAPublicKey) pk;
if ( dsapub.getParams() != null ) {
len = dsapub.getParams().getP().bitLength();
} else {
len = dsapub.getY().bitLength();
}
}
return len;
}