Example usage for org.bouncycastle.asn1.x509 Certificate getEncoded

List of usage examples for org.bouncycastle.asn1.x509 Certificate getEncoded

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Certificate getEncoded.

Prototype

public byte[] getEncoded() throws IOException 

Source Link

Document

Return the default BER or DER encoding for this object.

Usage

From source file:org.xipki.security.shell.ExtractCertFromCRLCommand.java

License:Open Source License

@Override
protected Object _doExecute() throws Exception {
    X509CRL crl = X509Util.parseCRL(crlFile);
    String oidExtnCerts = ObjectIdentifiers.id_xipki_ext_crlCertset.getId();
    byte[] extnValue = crl.getExtensionValue(oidExtnCerts);
    if (extnValue == null) {
        throw new IllegalCmdParamException("no certificate is contained in " + crlFile);
    }/* w w w .ja  v  a 2 s . c om*/

    extnValue = removingTagAndLenFromExtensionValue(extnValue);
    ASN1Set asn1Set = DERSet.getInstance(extnValue);
    int n = asn1Set.size();
    if (n == 0) {
        throw new CmdFailure("no certificate is contained in " + crlFile);
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(out);

    for (int i = 0; i < n; i++) {
        ASN1Encodable asn1 = asn1Set.getObjectAt(i);
        Certificate cert;
        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(asn1);
            cert = Certificate.getInstance(seq.getObjectAt(0));
        } catch (IllegalArgumentException e) {
            // backwards compatibility
            cert = Certificate.getInstance(asn1);
        }

        byte[] certBytes = cert.getEncoded();
        String sha1_fp_cert = SecurityUtil.sha1sum(certBytes);

        ZipEntry certZipEntry = new ZipEntry(sha1_fp_cert + ".der");
        zip.putNextEntry(certZipEntry);
        try {
            zip.write(certBytes);
        } finally {
            zip.closeEntry();
        }
    }

    zip.flush();
    zip.close();

    saveVerbose("extracted " + n + " certificates to", new File(outFile), out.toByteArray());
    return null;
}