java 讀取認證類以及key tool gui 1.7

來源:互聯網
上載者:User
Key Tool Gui 1.7

/**
* <p>Title: Light Weight APIs for crypto </p>
* <p>Description: 一個上海CA認證(根憑證和使用者認證)進行處理的例子</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: 中國資訊安全性群組織(CISO) </p>
* @author rainbow(webmaster)哈哈 拿老大的東西來添一添.ciso中有關於PKI的更多資料,歡迎你去看看呢
*希望能夠加入我們!
* @version 1.0.2003.0620
*/
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("認證版本:\t"+cert.getVersion());
        System.out.println("序號:\t\t"+cert.getSerialNumber().getValue().toString(16));
        System.out.println("演算法標識:\t"+cert.getSignatureAlgorithm().getObjectId().getId());
        System.out.println("簽發者:\t\t"+cert.getIssuer());
        System.out.println("開始時間:\t"+cert.getStartDate().getTime());
        System.out.println("結束時間:\t"+cert.getEndDate().getTime());
        System.out.println("主體名:\t\t"+cert.getSubject());
        System.out.print("簽名值:\t");
        DERBitString signature=cert.getSignature();
        String strSign=new String(Hex.encode(signature.getBytes()));
        System.out.println(strSign);
        System.out.println("主體公開金鑰:\t");
        SubjectPublicKeyInfo pukinfo=cert.getSubjectPublicKeyInfo();
        System.out.println("\t標識符:\t"+pukinfo.getAlgorithmId().getObjectId().getId());
        byte[] byPuk=pukinfo.getPublicKeyData().getBytes();
        String strPuk=new String(Hex.encode(byPuk));
        System.out.println("\t公開金鑰值:\t"+strPuk);
        // 認證的擴充資訊
        System.out.println("<<===========認證的擴充資訊==============>>");
        X509Extensions ext=cert.getTBSCertificate().getExtensions();
        // 15 --key usage     19 ---basic constrains
        // 31-- crl point     32 ---certificate policy
        getKeyUsage(ext);
        getBasicConstrains(ext);
        getCRLPoint(ext);
        getCertPolicy(ext);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return ;
    }
  }

  // 取密鑰的使用

  public void getKeyUsage(X509Extensions ext)
  {
    DERObjectIdentifier derOid = new DERObjectIdentifier("2.5.29.15");
    X509Extension item = null;
    boolean isCritical;
    ASN1OctetString value;
    try {
        item=ext.getExtension(derOid);
        isCritical=item.isCritical();
        value=item.getValue();
    }
    catch (Exception ex) {
        return;
    }
    System.out.println(new String(Hex.encode(value.getOctets())));
  }
  // 取基本限制
  public void getBasicConstrains(X509Extensions ext)
  {
    byte[] bytes = getExtensionBytes("2.5.29.19",ext);

    if (bytes != null)
    {
        try
        {
          DERInputStream dIn = new DERInputStream(new ByteArrayInputStream(bytes));
          ASN1Sequence   seq = (ASN1Sequence)dIn.readObject();

          if (seq.size() == 2)
          {
            if (((DERBoolean)seq.getObjectAt(0)).isTrue())
            {
                int pathlen=((DERInteger)seq.getObjectAt(1)).getValue().intValue();
                System.out.println("是CA認證\t"+"max path len="+pathlen);
            }
            else
            {
                System.out.println("不是ca認證!");
            }
          }
          else if (seq.size() == 1)
          {
            if (seq.getObjectAt(0) instanceof DERBoolean)
            {
                if (((DERBoolean)seq.getObjectAt(0)).isTrue())
                {
                  System.out.println(Integer.MAX_VALUE);
                }
            }
          }
        }
        catch (Exception e)
        {
          throw new RuntimeException("error processing key usage extension");
        }
    }
  }
  // 取crl分布點
  public void getCRLPoint(X509Extensions ext)
  {
    byte[] byContent = getExtensionBytes("2.5.29.31",ext);

    if (byContent != null)
    {
        try
        {
          DERInputStream dIn = new DERInputStream(new ByteArrayInputStream(byContent));
          ASN1Sequence   seq = (ASN1Sequence)dIn.readObject();
          int dpCount=seq.size();
          for(int i=0;i<dpCount;i++)
          {
            // 第一個分布點(DistributionPoint)
            ASN1Sequence point1=(ASN1Sequence)seq.getObjectAt(i);
            DERObject tobj=(DERTaggedObject)point1.getObjectAt(0);
            System.out.println("CRL分布點"+(i+1)+":");
            while(tobj instanceof DERTaggedObject&&!((DERTaggedObject)tobj).isEmpty())
            {
                System.out.println("\ttagNo:"+((DERTaggedObject)tobj).getTagNo());
                if(tobj instanceof DERTaggedObject)
                  tobj=((DERTaggedObject)tobj).getObject();
            }
            DEROctetString os=(DEROctetString)tobj.getDERObject();
            String str=new String(os.getOctets());
            System.out.println("\t"+str);
          }
        }
        catch (Exception e)
        {
          System.out.println("crl分布點處理出錯了!");
        }
    }
  }
  // 取憑證原則
  public void getCertPolicy(X509Extensions ext)
  {
    byte[] byContent = getExtensionBytes("2.5.29.32",ext);

    if (byContent != null)
    {
        try
        {
          DERInputStream dIn = new DERInputStream(new ByteArrayInputStream(byContent));
          ASN1Sequence   seq = (ASN1Sequence)dIn.readObject();
          //String dump = DERDump.dumpAsString(seq);
          // 調試輸出語句
          //System.out.println("憑證原則:"+dump);
          for(int i=0;i<seq.size();i++)
          {
            getPolicyInfo((ASN1Sequence)seq.getObjectAt(i));
          }
        }
        catch(Exception e)
        {
          e.printStackTrace();
        }
    }
  }
  private void getPolicyInfo(ASN1Sequence seq)
  {
    if(seq.size()==2)
    {
        DERObjectIdentifier objID=(DERObjectIdentifier)seq.getObjectAt(0);
        System.out.println("憑證原則標識:"+objID.getId());
        ASN1Sequence seqQualifier=(ASN1Sequence)seq.getObjectAt(1);
        for(int i=0;i<seqQualifier.size();i++)
          getPolicyQualifierInfo((ASN1Sequence)seqQualifier.getObjectAt(i));
    }
    else
        System.out.println("解析策略聲明時出錯!");
  }
  private void getPolicyQualifierInfo(ASN1Sequence seq)
  {
    if(seq.size()==2)
    {
        DERObjectIdentifier objID=(DERObjectIdentifier)seq.getObjectAt(0);
        System.out.println("策略宣告身份識別:"+objID.getId());
        DERIA5String ia5=(DERIA5String)seq.getObjectAt(1);
        System.out.println("聲明內容:"+ia5.getString());
    }
  }
  public static void main(String[] args) {
    CertManager cm = new CertManager();
    cm.getCert();
  }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.