Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream readObject.

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

From source file:org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier.java

License:Apache License

/**
 * Authority Information Access (AIA) is a non-critical extension in an X509 Certificate. This contains the
 * URL of the OCSP endpoint if one is available.
 * TODO: This might contain non OCSP urls as well. Handle this.
 *
 * @param cert is the certificate//from  ww  w . j av  a  2 s.c o m
 * @return a lit of URLs in AIA extension of the certificate which will hopefully contain an OCSP endpoint.
 * @throws CertificateVerificationException
 *
 */
private List<String> getAIALocations(X509Certificate cert) throws CertificateVerificationException {

    //Gets the DER-encoded OCTET string for the extension value for Authority information access Points
    byte[] aiaExtensionValue = cert.getExtensionValue(X509Extensions.AuthorityInfoAccess.getId());
    if (aiaExtensionValue == null)
        throw new CertificateVerificationException(
                "Certificate Doesnt have Authority Information Access points");
    //might have to pass an ByteArrayInputStream(aiaExtensionValue)
    ASN1InputStream asn1In = new ASN1InputStream(aiaExtensionValue);
    AuthorityInformationAccess authorityInformationAccess;

    try {
        DEROctetString aiaDEROctetString = (DEROctetString) (asn1In.readObject());
        ASN1InputStream asn1Inoctets = new ASN1InputStream(aiaDEROctetString.getOctets());
        ASN1Sequence aiaASN1Sequence = (ASN1Sequence) asn1Inoctets.readObject();
        authorityInformationAccess = new AuthorityInformationAccess(aiaASN1Sequence);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cannot read certificate to get OSCP urls", e);
    }

    List<String> ocspUrlList = new ArrayList<String>();
    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {

        GeneralName gn = accessDescription.getAccessLocation();
        if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
            DERIA5String str = DERIA5String.getInstance(gn.getName());
            String accessLocation = str.getString();
            ocspUrlList.add(accessLocation);
        }
    }
    if (ocspUrlList.isEmpty())
        throw new CertificateVerificationException("Cant get OCSP urls from certificate");

    return ocspUrlList;
}

From source file:org.apache.synapse.transport.utils.sslcert.crl.CRLVerifier.java

License:Apache License

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution Point"
 * extension in a X.509 certificate. If CRL distribution point extension is
 * unavailable, returns an empty list.//ww  w . j av  a 2s . c om
 */
private List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateVerificationException {

    //Gets the DER-encoded OCTET string for the extension value for CRLDistributionPoints
    byte[] crlDPExtensionValue = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId());
    if (crlDPExtensionValue == null)
        throw new CertificateVerificationException("Certificate doesn't have CRL " + "distribution points");
    //crlDPExtensionValue is encoded in ASN.1 format.
    ASN1InputStream asn1In = new ASN1InputStream(crlDPExtensionValue);
    // DER (Distinguished Encoding Rules) is one of ASN.1 encoding rules defined in ITU-T X.690,
    // 2002, specification. ASN.1 encoding rules can be used to encode any data object into a
    // binary file. Read the object in octets.
    CRLDistPoint distPoint;
    try {
        DEROctetString crlDEROctetString = (DEROctetString) asn1In.readObject();
        //Get Input stream in octets
        ASN1InputStream asn1InOctets = new ASN1InputStream(crlDEROctetString.getOctets());
        ASN1Primitive asn1Primitive = asn1InOctets.readObject();
        distPoint = CRLDistPoint.getInstance(asn1Primitive);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cannot read certificate to get CRL urls", e);
    }

    List<String> crlUrls = new ArrayList<String>();
    //Loop through ASN1Encodable DistributionPoints
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        //get ASN1Encodable DistributionPointName
        DistributionPointName dpn = dp.getDistributionPoint();
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            //Create ASN1Encodable General Names
            GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
            // Look for a URI
            //todo: May be able to check for OCSP url specifically.
            for (GeneralName genName : genNames) {
                if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    //DERIA5String contains an ascii string.
                    //A IA5String is a restricted character string type in the ASN.1 notation
                    String url = DERIA5String.getInstance(genName.getName()).getString().trim();
                    crlUrls.add(url);
                }
            }
        }
    }

    if (crlUrls.isEmpty()) {
        throw new CertificateVerificationException("Cant get CRL urls from certificate");
    }

    return crlUrls;
}

From source file:org.apache.synapse.transport.utils.sslcert.ocsp.OCSPVerifier.java

License:Apache License

/**
 * Authority Information Access (AIA) is a non-critical extension in an X509 Certificate. This contains the
 * URL of the OCSP endpoint if one is available.
 * TODO: This might contain non OCSP urls as well. Handle this.
 *
 * @param cert is the certificate/*from   ww w. j  a  va  2 s  .co m*/
 * @return a lit of URLs in AIA extension of the certificate which will hopefully contain an OCSP endpoint.
 * @throws CertificateVerificationException
 *
 */
private List<String> getAIALocations(X509Certificate cert) throws CertificateVerificationException {

    //Gets the DER-encoded OCTET string for the extension value for Authority information access Points
    byte[] aiaExtensionValue = cert.getExtensionValue(X509Extensions.AuthorityInfoAccess.getId());
    if (aiaExtensionValue == null) {
        throw new CertificateVerificationException(
                "Certificate doesn't have authority " + "information access points");
    }
    //might have to pass an ByteArrayInputStream(aiaExtensionValue)
    ASN1InputStream asn1In = new ASN1InputStream(aiaExtensionValue);
    AuthorityInformationAccess authorityInformationAccess;

    try {
        DEROctetString aiaDEROctetString = (DEROctetString) (asn1In.readObject());
        ASN1InputStream asn1InOctets = new ASN1InputStream(aiaDEROctetString.getOctets());
        ASN1Sequence aiaASN1Sequence = (ASN1Sequence) asn1InOctets.readObject();
        authorityInformationAccess = AuthorityInformationAccess.getInstance(aiaASN1Sequence);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cannot read certificate to get OCSP URLs", e);
    }

    List<String> ocspUrlList = new ArrayList<String>();
    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {

        GeneralName gn = accessDescription.getAccessLocation();
        if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
            DERIA5String str = DERIA5String.getInstance(gn.getName());
            String accessLocation = str.getString();
            ocspUrlList.add(accessLocation);
        }
    }
    if (ocspUrlList.isEmpty()) {
        throw new CertificateVerificationException("Cant get OCSP urls from certificate");
    }

    return ocspUrlList;
}

From source file:org.aselect.authspserver.authsp.pki.PKIManager.java

License:Open Source License

/**
 * private Helper function for DER Decoding. <br>
 * <br>//from www . j a  v a2  s . com
 * 
 * @param baExtensionValue
 *            the ba extension value
 * @return a DER object
 * @throws ASelectException
 *             the a select exception
 */
private DERObject getDERObject(byte[] baExtensionValue) throws ASelectException {
    String sMethod = "getDERObject";
    try {
        ASN1InputStream oInputStream = new ASN1InputStream(new ByteArrayInputStream(baExtensionValue));
        byte[] baExtOctets = ((ASN1OctetString) oInputStream.readObject()).getOctets();
        oInputStream = new ASN1InputStream(new ByteArrayInputStream(baExtOctets));
        return oInputStream.readObject();
    } catch (IOException e) {
        _systemLogger.log(Level.WARNING, MODULE, sMethod, e.getMessage(), e);
        throw new ASelectException(Errors.PKI_INTERNAL_SERVER_ERROR, e);
    }
}

From source file:org.broad.igv.feature.AminoAcidManager.java

License:LGPL

/**
 * Load codon tables from the specified path. If any exceptions occur
 * while loading, no changes are made to this instance.
 * <p/>// w  ww  .  java2 s  .com
 * Note that the new codon tables are ADDED to the existing tables
 * <p/>
 * The currentCodonTable is set to be the codonTable with id = defaultid if present
 * If not, the first one in the array is set as default
 *
 * @param codonTablesPath
 * @return
 */
synchronized void loadCodonTables(String codonTablesPath) throws IOException, JsonParseException {
    LinkedHashMap<CodonTableKey, CodonTable> newCodonTables = new LinkedHashMap<CodonTableKey, CodonTable>(20);
    CodonTable defaultCodonTable = null;

    InputStream is = AminoAcidManager.class.getResourceAsStream(codonTablesPath);
    if (is == null) {
        is = ParsingUtils.openInputStream(codonTablesPath);
    }

    if (codonTablesPath.endsWith(".json")) {
        JsonObject allData = readJSONFromStream(is);
        int defaultId = -1;
        defaultId = allData.get("defaultid").getAsInt();
        JsonArray codonArray = allData.get("Genetic-code-table").getAsJsonArray();
        if (codonArray.size() == 0) {
            throw new JsonParseException("JSON File has empty array for Genetic-code-table");
        }
        for (int ca = 0; ca < codonArray.size(); ca++) {
            CodonTable curTable = CodonTable.createFromJSON(codonTablesPath,
                    codonArray.get(ca).getAsJsonObject());
            newCodonTables.put(curTable.getKey(), curTable);
            if (defaultCodonTable == null || curTable.getId() == defaultId) {
                defaultCodonTable = curTable;
            }
        }
    } else if (codonTablesPath.endsWith(".asn1") || codonTablesPath.endsWith(".val")) {
        ASN1InputStream ASNis = new ASN1InputStream(is);
        ASN1Primitive obj = ASNis.readObject();
        ASN1Set set = (ASN1Set) obj;
        //Array of different genetic code tables
        ASN1Encodable[] codonArray = set.toArray();
        if (codonArray.length == 0) {
            throw new RuntimeException("ASN1 File has empty array for Genetic-code-table");
        }
        for (ASN1Encodable aCodonArray : codonArray) {
            CodonTable curTable = CodonTable.createFromASN1(codonTablesPath, aCodonArray);
            newCodonTables.put(curTable.getKey(), curTable);
            if (defaultCodonTable == null) {
                defaultCodonTable = curTable;
            }
        }
    } else {
        throw new IllegalArgumentException("Unknown file type, must be .json or .asn1");
    }

    allCodonTables.putAll(newCodonTables);
    currentCodonTable = defaultCodonTable;
}

From source file:org.candlepin.CRLWriteBenchmark.java

License:Open Source License

@Benchmark
@Fork(value = 1, jvmArgsAppend = { "-Xloggc:gc_in_memory_write.log", "-verbose:gc", "-XX:+PrintGCDetails",
        "-XX:+PrintGCTimeStamps" })
public void inMemory() {
    ASN1InputStream stream = null;
    try {//from w w  w. j  av  a  2s . co m
        stream = new ASN1InputStream(new BufferedInputStream(new FileInputStream(crlFile)));
        DERObject o = stream.readObject();

        X509CRLHolder oldCrl = new X509CRLHolder(o.getDEREncoded());

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());
        crlBuilder.addCRL(oldCrl);

        crlBuilder.addCRLEntry(new BigInteger("25000000000"), new Date(), CRLReason.unspecified);

        X509CRLHolder holder = crlBuilder.build(signer);
        X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder);

        File newCrlFile = File.createTempFile("new_crl", ".der");
        FileUtils.writeByteArrayToFile(newCrlFile, crl.getEncoded());
        System.out.println("\nWrote new crl to " + newCrlFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.candlepin.pki.impl.BouncyCastlePKIUtility.java

License:Open Source License

@Override
public String decodeDERValue(byte[] value) {
    ASN1InputStream vis = null;
    ASN1InputStream decoded = null;
    try {//from  ww  w.j av  a  2 s  .  c  o m
        vis = new ASN1InputStream(value);
        decoded = new ASN1InputStream(((DEROctetString) vis.readObject()).getOctets());

        return decoded.readObject().toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (vis != null) {
            try {
                vis.close();
            } catch (IOException e) {
                log.warn("failed to close ASN1 stream", e);
            }
        }

        if (decoded != null) {
            try {
                decoded.close();
            } catch (IOException e) {
                log.warn("failed to close ASN1 stream", e);
            }
        }
    }
}

From source file:org.candlepin.util.X509CRLStreamWriter.java

License:Open Source License

public synchronized X509CRLStreamWriter preScan(InputStream crlToChange, CRLEntryValidator validator)
        throws IOException {
    if (locked) {
        throw new IllegalStateException("Cannot modify a locked stream.");
    }//  w  w  w.  j av a2s .  com

    if (preScanned) {
        throw new IllegalStateException("preScan has already been run.");
    }

    X509CRLEntryStream reaperStream = null;
    ASN1InputStream asn1In = null;

    try {
        reaperStream = new X509CRLEntryStream(crlToChange);
        try {
            if (!reaperStream.hasNext()) {
                emptyCrl = true;
                preScanned = true;
                return this;
            }

            while (reaperStream.hasNext()) {
                X509CRLEntryObject entry = reaperStream.next();
                if (validator != null && validator.shouldDelete(entry)) {
                    deletedEntries.add(entry.getSerialNumber());
                    deletedEntriesLength += entry.getEncoded().length;
                }
            }
        } catch (CRLException e) {
            throw new IOException("Could not read CRL entry", e);
        }

        /* At this point, crlToChange is at the point where the crlExtensions would
         * be.  RFC 5280 says that "Conforming CRL issuers are REQUIRED to include
         * the authority key identifier (Section 5.2.1) and the CRL number (Section 5.2.3)
         * extensions in all CRLs issued.
         */
        byte[] oldExtensions = null;
        DERObject o;
        asn1In = new ASN1InputStream(crlToChange);
        while ((o = asn1In.readObject()) != null) {
            if (o instanceof DERSequence) {
                // Now we are at the signatureAlgorithm
                DERSequence seq = (DERSequence) o;
                if (seq.getObjectAt(0) instanceof DERObjectIdentifier) {
                    signingAlg = new AlgorithmIdentifier(seq);
                    digestAlg = new DefaultDigestAlgorithmIdentifierFinder().find(signingAlg);

                    try {
                        // Build the signer
                        this.signer = new RSADigestSigner(createDigest(digestAlg));
                        signer.init(true,
                                new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent()));
                    } catch (CryptoException e) {
                        throw new IOException(
                                "Could not create RSADigest signer for " + digestAlg.getAlgorithm());
                    }
                }
            } else if (o instanceof DERBitString) {
                oldSigLength = o.getDEREncoded().length;
            } else {
                if (oldExtensions != null) {
                    throw new IllegalStateException("Already read in CRL extensions.");
                }
                oldExtensions = ((DERTaggedObject) o).getDEREncoded();
            }
        }

        if (oldExtensions == null) {
            /* v1 CRLs (defined in RFC 1422) don't require extensions but all new
             * CRLs should be v2 (defined in RFC 5280).  In the extremely unlikely
             * event that someone is working with a v1 CRL, we handle it here although
             * we print a warning.
             */
            preScanned = true;
            newExtensions = null;
            extensionsDelta = 0;
            log.warn("The CRL you are modifying is a version 1 CRL."
                    + " Please investigate moving to a version 2 CRL by adding the CRL Number"
                    + " and Authority Key Identifier extensions.");
            return this;
        }
        newExtensions = updateExtensions(oldExtensions);
        extensionsDelta = (newExtensions.length - oldExtensions.length)
                + findHeaderBytesDelta(oldExtensions.length, newExtensions.length);
    } finally {
        if (reaperStream != null) {
            reaperStream.close();
        }
        IOUtils.closeQuietly(asn1In);
    }
    preScanned = true;
    return this;
}

From source file:org.candlepin.util.X509CRLStreamWriter.java

License:Open Source License

protected void writeToEmptyCrl(OutputStream out) throws IOException {
    ASN1InputStream asn1in = null;
    try {//from  w ww .j a  va2s.  c o  m
        asn1in = new ASN1InputStream(crlIn);
        DERSequence certListSeq = (DERSequence) asn1in.readObject();
        CertificateList certList = new CertificateList(certListSeq);
        X509CRLHolder oldCrl = new X509CRLHolder(certList);

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(oldCrl.getIssuer(), new Date());
        crlBuilder.addCRL(oldCrl);

        Date now = new Date();
        Date oldNextUpdate = certList.getNextUpdate().getDate();
        Date oldThisUpdate = certList.getThisUpdate().getDate();

        Date nextUpdate = new Date(now.getTime() + (oldNextUpdate.getTime() - oldThisUpdate.getTime()));
        crlBuilder.setNextUpdate(nextUpdate);

        for (Object o : oldCrl.getExtensionOIDs()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) o;
            X509Extension ext = oldCrl.getExtension(oid);

            if (oid.equals(X509Extension.cRLNumber)) {
                DEROctetString octet = (DEROctetString) ext.getValue().getDERObject();
                DERInteger currentNumber = (DERInteger) DERTaggedObject.fromByteArray(octet.getOctets());
                DERInteger nextNumber = new DERInteger(currentNumber.getValue().add(BigInteger.ONE));

                crlBuilder.addExtension(oid, ext.isCritical(), nextNumber);
            } else if (oid.equals(X509Extension.authorityKeyIdentifier)) {
                crlBuilder.addExtension(oid, ext.isCritical(),
                        new AuthorityKeyIdentifierStructure(ext.getValue().getDEREncoded()));
            }
        }

        for (DERSequence entry : newEntries) {
            // XXX: This is all a bit messy considering the user already passed in the serial, date
            // and reason.
            BigInteger serial = ((DERInteger) entry.getObjectAt(0)).getValue();
            Date revokeDate = ((Time) entry.getObjectAt(1)).getDate();
            int reason = CRLReason.unspecified;
            if (entry.size() == 3) {
                X509Extensions extensions = (X509Extensions) entry.getObjectAt(2);
                X509Extension reasonExt = extensions.getExtension(X509Extension.reasonCode);

                if (reasonExt != null) {
                    reason = ((DEREnumerated) reasonExt.getParsedValue()).getValue().intValue();
                }
            }
            crlBuilder.addCRLEntry(serial, revokeDate, reason);
        }

        RSAKeyParameters keyParams = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());

        signingAlg = oldCrl.toASN1Structure().getSignatureAlgorithm();
        digestAlg = new DefaultDigestAlgorithmIdentifierFinder().find(signingAlg);

        ContentSigner s;
        try {
            s = new BcRSAContentSignerBuilder(signingAlg, digestAlg).build(keyParams);
            X509CRLHolder newCrl = crlBuilder.build(s);
            out.write(newCrl.getEncoded());
        } catch (OperatorCreationException e) {
            throw new IOException("Could not sign CRL", e);
        }
    } finally {
        IOUtils.closeQuietly(asn1in);
    }
}

From source file:org.ccnx.ccn.impl.security.crypto.util.CryptoUtil.java

License:Open Source License

/**
 * Helper function to decode DER content.
 * @param decodable content to decode//  ww w  .  j  a  v  a 2 s.c  o m
 * @return generic DERObject, result of decoding
 * @throws CertificateEncodingException if there is a problem decoding the content
 */
public static DERObject decode(byte[] decodable) throws CertificateEncodingException {
    DERObject dobj = null;
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(decodable);
        ASN1InputStream dis = new ASN1InputStream(bais);
        dobj = dis.readObject();
        dis.close();
    } catch (IOException ex) {
        StringBuffer sb = new StringBuffer();
        sb.append("decode error - length " + decodable.length);
        for (byte b : decodable)
            sb.append(" " + Integer.toHexString((int) b));
        Log.severe(sb.toString());
        for (StackTraceElement ste : ex.getStackTrace())
            Log.severe(ste.toString());
        throw new CertificateEncodingException("Cannot encode: " + ex.toString());
    }
    return dobj;
}