Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

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

Introduction

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

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:org.apache.http.contrib.auth.BouncySpnegoTokenGenerator.java

License:Apache License

public byte[] generateSpnegoDERObject(byte[] kerbTicket) throws IOException {
    DEROctetString ourKerberosTicket = new DEROctetString(kerbTicket);

    DERSequence kerbOidSeq = new DERSequence(kerbOid);
    DERTaggedObject tagged0 = new DERTaggedObject(0, kerbOidSeq);
    DERTaggedObject tagged2 = new DERTaggedObject(2, ourKerberosTicket);
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(tagged0);//from  w w  w .  ja  v a  2s  .c o  m
    v.add(tagged2);
    DERSequence seq = new DERSequence(v);
    DERTaggedObject taggedSpnego = new DERTaggedObject(0, seq);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ASN1OutputStream asn1Out = new ASN1OutputStream(out);

    ASN1Object spnegoOIDASN1 = (ASN1Object) spnegoOid.toASN1Object();
    ASN1Object taggedSpnegoASN1 = (ASN1Object) taggedSpnego.toASN1Object();

    int length = spnegoOIDASN1.getDEREncoded().length + taggedSpnegoASN1.getDEREncoded().length;
    byte[] lenBytes = writeLength(length);
    byte[] appWrap = new byte[lenBytes.length + 1];

    appWrap[0] = 0x60;
    for (int i = 1; i < appWrap.length; i++) {
        appWrap[i] = lenBytes[i - 1];
    }

    asn1Out.write(appWrap);
    asn1Out.writeObject(spnegoOid.toASN1Object());
    asn1Out.writeObject(taggedSpnego.toASN1Object());

    byte[] app = out.toByteArray();
    ASN1InputStream in = new ASN1InputStream(app);

    if (log.isDebugEnabled()) {
        int skip = 12;
        byte[] manipBytes = new byte[app.length - skip];
        for (int i = skip; i < app.length; i++) {
            manipBytes[i - skip] = app[i];
        }
        ASN1InputStream ourSpnego = new ASN1InputStream(manipBytes);
        log.debug(ASN1Dump.dumpAsString(ourSpnego.readObject()));
    }

    return in.readObject().getDEREncoded();
}

From source file:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java

License:Apache License

private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        throws GeneralSecurityException, IOException {
    ASN1InputStream asn1inputstream = new ASN1InputStream(
            new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure
            .getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo()
            .getAlgorithmId();/*from   w  w  w. j  ava2s. c om*/
    IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(),
            tbscertificatestructure.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getObjectId().getId());
    cipher.init(1, x509certificate.getPublicKey());
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
}

From source file:org.apache.poi.poifs.crypt.dsig.facets.XAdESXLSignatureFacet.java

License:Apache License

private BigInteger getCrlNumber(X509CRL crl) {
    try {/* w  w  w .java  2  s. c  om*/
        byte[] crlNumberExtensionValue = crl.getExtensionValue(Extension.cRLNumber.getId());
        if (null == crlNumberExtensionValue) {
            return null;
        }

        @SuppressWarnings("resource")
        ASN1InputStream asn1InputStream = new ASN1InputStream(crlNumberExtensionValue);
        ASN1OctetString octetString = (ASN1OctetString) asn1InputStream.readObject();
        byte[] octets = octetString.getOctets();
        asn1InputStream = new ASN1InputStream(octets);
        ASN1Integer integer = (ASN1Integer) asn1InputStream.readObject();
        BigInteger crlNumber = integer.getPositiveValue();
        return crlNumber;
    } catch (Exception e) {
        throw new RuntimeException("I/O error: " + e.getMessage(), e);
    }
}

From source file:org.apache.synapse.transport.certificatevalidation.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.//from   w w w .j  a v  a2s  .co  m
 */
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());
        DERObject crlDERObject = asn1InOctets.readObject();
        distPoint = CRLDistPoint.getInstance(crlDERObject);
    } 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.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/* w  w  w .  j a  v  a 2s .  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./*from   w  w  w. j  av a 2s  . c o  m*/
 */
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// w  ww . j  a  v  a 2 s . com
 * @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 a  2s  .  co  m
 * 
 * @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/>//from  w ww .  j a  v  a2s. c om
 * 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 ww  w .j ava 2 s.c o 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();
            }
        }
    }
}