Java解析证书的例子(一)

2014-11-24 01:08:58 · 作者: · 浏览: 2

import java.io.*;
import org.bouncycastle.asn1.*;
import org.bouncycastle.asn1.util.*;
import org.bouncycastle.asn1.x509.*;
import org.bouncycastle.util.encoders.*;
public class CertManager {
String eoid[][]={
{new String("Subject Key Identifier"), new String("2.5.29.14")},
{new String("Key Usage"), new String("2.5.29.15")},
{new String("Private Key Usage Period"),new String("2.5.29.16")},
{new String("Subject Alternative Name"),new String("2.5.29.17")},
{new String("Issuer Alternative Name"), new String("2.5.29.18")},
{new String("Basic Constraints"), new String("2.5.29.19")},
{new String("CRL Number"), new String("2.5.29.20")},
{new String("Reason code"), new String("2.5.29.21")},
{new String("Hold Instruction Code"), new String("2.5.29.23")},
{new String("Invalidity Date"), new String("2.5.29.24")},
{new String("Delta CRL indicator"), new String("2.5.29.27")},
{new String("Issuing Distribution Point"),new String("2.5.29.28")},
{new String("Certificate Issuer"), new String("2.5.29.29")},
{new String("Name Constraints"), new String("2.5.29.30")},
{new String("CRL Distribution Points"), new String("2.5.29.31")},
{new String("Certificate Policies"), new String("2.5.29.32")},
{new String("Policy Mappings"), new String("2.5.29.33")},
{new String("Authority Key Identifier"),new String("2.5.29.35")},
{new String("Policy Constraints"), new String("2.5.29.36")},
{new String("Extended Key Usage"), new String("2.5.29.37")}};
byte buf[];
public CertManager() {
int fLength=0;
try {
FileInputStream fis=new FileInputStream("..\mycert\ca.der");
fLength=fis.available();
buf=new byte[fLength];
fis.read(buf,0,fLength);
}
catch (Exception ex) {
System.out.println("读证书文件出错!");
return;
}
}
public byte[] getExtensionBytes(String oid,X509Extensions exts)
{
if (exts != null)
{
X509Extension ext = exts.getExtension(new DERObjectIdentifier(oid));
if (ext != null)
{
return ext.getValue().getOctets();
}
}
return null;
}
public void getCert()
{

ByteArrayInputStream bIn;
DERInputStream dIn;
String dump = "";

try
{
bIn = new ByteArrayInputStream(buf);
dIn = new DERInputStream(bIn);

ASN1Sequence seq = (ASN1Sequence)dIn.readObject();
//dump = DERDump.dumpAsString(seq);
// 调试输出语句
//System.out.println(dump);
// 证书的基本信息
System.out.println("<<=============证书的基本信息===============>>");
X509CertificateStructure cert = new X509CertificateStructure(seq);
System.out.println("证书版本: "+cert.getVersion());
System.out.println("序列号: "+cert.getSerialNumber().getValue().toString(16));
System.out.println("算法标识: "+cert.getSignatureAlgorithm().getObjectId().getId());
System.out.println("签发者: "+cert.getIssuer());
System.out.println("开始时间: "+cert.getStartDate().getTime());
System.out.println("结束时间: "+cert.getEndDate().ge