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.icepdf.core.pobjects.acroform.signature.certificates.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 a 2 s.c o m
 */
public static List<String> getCrlDistributionPoints(X509Certificate cert)
        throws CertificateParsingException, IOException {
    byte[] crldpExt = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (crldpExt == null) {
        return new ArrayList<String>();
    }
    ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt));
    ASN1Primitive derObjCrlDP = oAsnInStream.readObject();
    DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP;
    byte[] crldpExtOctets = dosCrlDP.getOctets();
    ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets));
    ASN1Primitive derObj2 = oAsnInStream2.readObject();
    CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
    List<String> crlUrls = new ArrayList<String>();
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        DistributionPointName dpn = dp.getDistributionPoint();
        // Look for URIs in fullName
        if (dpn != null) {
            if (dpn.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
                // Look for an URI
                for (GeneralName genName : genNames) {
                    if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                        String url = DERIA5String.getInstance(genName.getName()).getString();
                        crlUrls.add(url);
                    }
                }
            }
        }
    }
    return crlUrls;
}

From source file:org.icepdf.core.pobjects.acroform.signature.Pkcs1Validator.java

License:Apache License

public void init() throws SignatureIntegrityException {
    SignatureDictionary signatureDictionary = signatureFieldDictionary.getSignatureDictionary();
    announceSignatureType(signatureDictionary);
    // start the decode of the raw type.
    StringObject stringObject = signatureDictionary.getContents();
    // make sure we don't loose any bytes converting the string in the raw.
    byte[] cmsData = Utils.convertByteCharSequenceToByteArray(stringObject.getLiteralString());
    // get the certificate
    stringObject = signatureDictionary.getCertString();
    // make sure we don't loose any bytes converting the string in the raw.
    byte[] certsKey = Utils.convertByteCharSequenceToByteArray(stringObject.getLiteralString());

    try {//from  w  w  w.  j av a  2 s . c  o  m
        X509CertParser x509CertParser = new X509CertParser();
        x509CertParser.engineInit(new ByteArrayInputStream(certsKey));
        certificateChain = x509CertParser.engineReadAll();
        signerCertificate = (X509Certificate) certificateChain.iterator().next();

        // content data is encrypted using the cert above.
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cmsData));
        ASN1Primitive tmp = asn1InputStream.readObject();
        messageDigest = ((ASN1OctetString) tmp).getOctets();

        String provider = signatureDictionary.getFilter().getName();
        digestAlgorithmIdentifier = OIWObjectIdentifiers.idSHA1.getId();
        signatureAlgorithmIdentifier = PKCSObjectIdentifiers.rsaEncryption.getId();
        // basic creation and public key check which should throw any format errors.
        createSignature(signerCertificate.getPublicKey(), provider, signatureAlgorithmIdentifier,
                digestAlgorithmIdentifier);

        // Use RSA/ECB/NoPadding do decrypt the message digest
        Cipher asymmetricCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        // initialize your cipher
        asymmetricCipher.init(Cipher.DECRYPT_MODE, signerCertificate.getPublicKey());
        // assuming, cipherText is a byte array containing your encrypted message
        messageDigest = asymmetricCipher.doFinal(messageDigest);
        // trim the padding bytes
        if (messageDigest.length > 20) {
            // You can create the ASN.1 BER encoding of an MD5, SHA-1, or SHA-256 value by prepending these strings to
            // the 16-byte or 20-byte hash values, respectively:
            // We always assume sha1 which is:
            //    ref: sha1   : X'30213009 06052B0E 03021A05 000414'
            //    ref: SHA-256: X'3031300D 06096086 48016503 04020105 000420'
            //    ref: MD5:     X'3020300C 06082A86 4886F70D 02050500 0410'
            byte[] trunkedMD = new byte[20];
            System.arraycopy(messageDigest, 15, trunkedMD, 0, 20);
            messageDigest = trunkedMD;
        }
    } catch (Exception e) {
        throw new SignatureIntegrityException(e);
    }
    initialized = true;
}

From source file:org.identityconnectors.racf.BouncyCastlePEUtilities.java

License:Open Source License

public String getPassword(byte[] envelope) {
    ASN1InputStream aIn = null;
    try {/*from w w  w.j a  va2 s. c  om*/
        aIn = new ASN1InputStream(envelope);
        Object o = null;
        DEROctetString oString = null;

        while ((o = aIn.readObject()) != null) {
            if (o instanceof DERSequence) {

                // identifier (1.2.840.113549.1.7.1)
                DERSequence seq = (DERSequence) o;
                if (seq.size() >= 2 && seq.getObjectAt(0) instanceof DERObjectIdentifier
                        && "1.2.840.113549.1.7.1".equals(((DERObjectIdentifier) seq.getObjectAt(0)).getId())) {

                    if (seq.getObjectAt(1) instanceof DERTaggedObject
                            && ((DERTaggedObject) seq.getObjectAt(1)).getObject() instanceof DEROctetString) {

                        oString = (DEROctetString) ((DERTaggedObject) seq.getObjectAt(1)).getObject();
                        break;
                    }
                }
            }
        }
        aIn.close();
        aIn = null;
        String pw = null;
        if (oString != null) {
            aIn = new ASN1InputStream(oString.getOctets());
            DERSequence seq = (DERSequence) aIn.readObject();
            if (seq.getObjectAt(2) instanceof DERUTF8String) {
                pw = ((DERUTF8String) seq.getObjectAt(2)).getString();
            }
            aIn.close();
            aIn = null;
        }
        return pw;
    } catch (IOException e) {
        try {
            if (aIn != null)
                aIn.close();
        } catch (IOException e2) {
        }
        throw ConnectorException.wrap(e);
    }
}

From source file:org.italiangrid.voms.asn1.VOMSACGenerator.java

License:Apache License

private DEREncodable getCertAsDEREncodable(X509Certificate cert) {

    try {/* w  ww.  j a v a2 s.com*/
        byte[] certBytes = cert.getEncoded();

        ByteArrayInputStream bais = new ByteArrayInputStream(certBytes);
        ASN1InputStream is = new ASN1InputStream(bais);
        DERObject derCert = is.readObject();
        is.close();
        return derCert;

    } catch (CertificateEncodingException e) {
        throw new VOMSError("Error encoding X509 certificate: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new VOMSError("Error encoding X509 certificate: " + e.getMessage(), e);
    }

}

From source file:org.italiangrid.voms.asn1.VOMSACUtils.java

License:Apache License

/**
 * Deserializes the VOMS Attribute certificates in a given certificate
 * extension/*from   ww  w .  ja va2  s.c om*/
 * 
 * @param vomsExtension
 *          the VOMS extension
 * @return the possibly empty {@link List} of {@link AttributeCertificate}
 *         extracted from a given extension
 * @throws IOException
 *          in case of deserialization errors
 */
public static List<AttributeCertificate> getACsFromVOMSExtension(byte[] vomsExtension) throws IOException {

    List<AttributeCertificate> acs = null;

    if (vomsExtension == null)
        return Collections.emptyList();

    acs = new ArrayList<AttributeCertificate>();

    // Convert extension to a DEROctetString
    ASN1InputStream asn1Stream = new ASN1InputStream(new ByteArrayInputStream(vomsExtension));
    byte[] payload = ((DEROctetString) asn1Stream.readObject()).getOctets();

    asn1Stream.close();

    asn1Stream = new ASN1InputStream(new ByteArrayInputStream(payload));

    // VOMS extension is SEQUENCE of SET of AttributeCertificate
    // now, SET is an ordered sequence, and an AC is a sequence as
    // well -- thus the three nested ASN.1 sequences below...
    ASN1Sequence baseSequence = (ASN1Sequence) asn1Stream.readObject();
    asn1Stream.close();

    @SuppressWarnings("unchecked")
    Enumeration<ASN1Sequence> setSequence = baseSequence.getObjects();

    while (setSequence.hasMoreElements()) {

        ASN1Sequence acSequence = setSequence.nextElement();

        @SuppressWarnings("unchecked")
        Enumeration<ASN1Sequence> theACs = acSequence.getObjects();

        while (theACs.hasMoreElements()) {

            AttributeCertificate parsedAC = new AttributeCertificate(theACs.nextElement());
            acs.add(parsedAC);
        }
    }

    return acs;
}

From source file:org.italiangrid.voms.request.impl.DefaultVOMSACService.java

License:Apache License

/**
 * Extracts an AC from a VOMS response/* w ww . j a va 2 s  . c o  m*/
 * 
 * @param request
 *          the request
 * @param response
 *          the received response
 * @return a possibly <code>null</code> {@link AttributeCertificate} object
 */
protected AttributeCertificate getACFromResponse(VOMSACRequest request, VOMSResponse response) {

    byte[] acBytes = response.getAC();

    if (acBytes == null)
        return null;

    ASN1InputStream asn1InputStream = new ASN1InputStream(acBytes);

    AttributeCertificate attributeCertificate = null;

    try {

        attributeCertificate = AttributeCertificate.getInstance(asn1InputStream.readObject());

        asn1InputStream.close();
        return attributeCertificate;

    } catch (Throwable e) {

        requestListener.notifyVOMSRequestFailure(request, null,
                new VOMSError("Error unmarshalling VOMS AC. Cause: " + e.getMessage(), e));

        return null;
    }
}

From source file:org.jivesoftware.multiplexer.net.TLSStreamHandler.java

License:Open Source License

/**
 * Returns the JID representation of an XMPP entity contained as a SubjectAltName extension
 * in the certificate. If none was found then return <tt>null</tt>.
 *
 * @param certificate the certificate presented by the remote entity.
 * @return the JID representation of an XMPP entity contained as a SubjectAltName extension
 *         in the certificate. If none was found then return <tt>null</tt>.
 *///from w w  w  . ja  v  a  2  s . com
private static List<String> getSubjectAlternativeNames(X509Certificate certificate) {
    List<String> identities = new ArrayList<String>();
    try {
        Collection altNames = certificate.getSubjectAlternativeNames();
        // Check that the certificate includes the SubjectAltName extension
        if (altNames == null) {
            return Collections.emptyList();
        }
        // Use the type OtherName to search for the certified server name
        for (Iterator lists = altNames.iterator(); lists.hasNext();) {
            List item = (List) lists.next();
            Integer type = (Integer) item.get(0);
            if (type.intValue() == 0) {
                // Type OtherName found so return the associated value
                try {
                    // Value is encoded using ASN.1 so decode it to get the server's identity
                    ASN1InputStream decoder = new ASN1InputStream((byte[]) item.toArray()[1]);
                    DEREncodable encoded = decoder.readObject();
                    encoded = ((DERSequence) encoded).getObjectAt(1);
                    encoded = ((DERTaggedObject) encoded).getObject();
                    encoded = ((DERTaggedObject) encoded).getObject();
                    String identity = ((DERUTF8String) encoded).getString();
                    // Add the decoded server name to the list of identities
                    identities.add(identity);
                } catch (UnsupportedEncodingException e) {
                } catch (IOException e) {
                } catch (Exception e) {
                    Log.error("Error decoding subjectAltName", e);
                }
            }
            // Other types are not good for XMPP so ignore them
            if (Log.isDebugEnabled()) {
                Log.debug("SubjectAltName of invalid type found: " + certificate);
            }
        }
    } catch (CertificateParsingException e) {
        Log.error("Error parsing SubjectAltName in certificate: " + certificate, e);
    }
    return identities;
}

From source file:org.jivesoftware.util.CertificateManager.java

License:Open Source License

/**
 * Returns the JID representation of an XMPP entity contained as a SubjectAltName extension
 * in the certificate. If none was found then return <tt>null</tt>.
 *
 * @param certificate the certificate presented by the remote entity.
 * @return the JID representation of an XMPP entity contained as a SubjectAltName extension
 *         in the certificate. If none was found then return <tt>null</tt>.
 *///w ww.ja  v a 2  s. c  o  m
private static List<String> getSubjectAlternativeNames(X509Certificate certificate) {
    List<String> identities = new ArrayList<String>();
    try {
        Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
        // Check that the certificate includes the SubjectAltName extension
        if (altNames == null) {
            return Collections.emptyList();
        }
        // Use the type OtherName to search for the certified server name
        for (List<?> item : altNames) {
            Integer type = (Integer) item.get(0);
            if (type == 0) {
                // Type OtherName found so return the associated value
                try {
                    // Value is encoded using ASN.1 so decode it to get the server's identity
                    ASN1InputStream decoder = new ASN1InputStream((byte[]) item.get(1));
                    Object object = decoder.readObject();
                    ASN1Sequence otherNameSeq = null;
                    if (object != null && object instanceof ASN1Sequence) {
                        otherNameSeq = (ASN1Sequence) object;
                    } else {
                        continue;
                    }
                    // Check the object identifier
                    ASN1ObjectIdentifier objectId = (ASN1ObjectIdentifier) otherNameSeq.getObjectAt(0);
                    Log.debug("Parsing otherName for subject alternative names: " + objectId.toString());

                    if (!OTHERNAME_XMPP_OID.equals(objectId.getId())) {
                        // Not a XMPP otherName
                        Log.debug("Ignoring non-XMPP otherName, " + objectId.getId());
                        continue;
                    }

                    // Get identity string
                    try {
                        final String identity;
                        ASN1Encodable o = otherNameSeq.getObjectAt(1);
                        if (o instanceof DERTaggedObject) {
                            ASN1TaggedObject ato = DERTaggedObject.getInstance(o);
                            Log.debug("... processing DERTaggedObject: " + ato.toString());
                            // TODO: there's bound to be a better way...
                            identity = ato.toString().substring(ato.toString().lastIndexOf(']') + 1).trim();
                        } else {
                            DERUTF8String derStr = DERUTF8String.getInstance(o);
                            identity = derStr.getString();
                        }
                        if (identity != null && identity.length() > 0) {
                            // Add the decoded server name to the list of identities
                            identities.add(identity);
                        }
                        decoder.close();
                    } catch (IllegalArgumentException ex) {
                        // OF-517: othername formats are extensible. If we don't recognize the format, skip it.
                        Log.debug("Cannot parse altName, likely because of unknown record format.", ex);
                    }
                } catch (UnsupportedEncodingException e) {
                    // Ignore
                } catch (IOException e) {
                    // Ignore
                } catch (Exception e) {
                    Log.error("Error decoding subjectAltName", e);
                }
            }
            // Other types are not applicable for XMPP, so silently ignore them
        }
    } catch (CertificateParsingException e) {
        Log.error("Error parsing SubjectAltName in certificate: " + certificate.getSubjectDN(), e);
    }
    return identities;
}

From source file:org.jmrtd.lds.CardAccessFile.java

License:Open Source License

protected void readContent(InputStream inputStream) throws IOException {
    securityInfos = new HashSet<SecurityInfo>();
    ASN1InputStream asn1In = new ASN1InputStream(inputStream);
    ASN1Set set = (ASN1Set) asn1In.readObject();
    for (int i = 0; i < set.size(); i++) {
        ASN1Primitive object = set.getObjectAt(i).toASN1Primitive();
        SecurityInfo securityInfo = SecurityInfo.getInstance(object);
        if (securityInfo == null) {
            continue;
        } /* NOTE: skipping this unsupported SecurityInfo */
        securityInfos.add(securityInfo);
    }//from  ww  w  .  j av  a 2s  .c om
}

From source file:org.jmrtd.lds.DG14File.java

License:Open Source License

protected void readContent(InputStream inputStream) throws IOException {
    securityInfos = new HashSet<SecurityInfo>();
    ASN1InputStream asn1In = new ASN1InputStream(inputStream);
    ASN1Set set = (ASN1Set) asn1In.readObject();
    for (int i = 0; i < set.size(); i++) {
        ASN1Primitive object = set.getObjectAt(i).toASN1Primitive();
        SecurityInfo securityInfo = SecurityInfo.getInstance(object);
        if (securityInfo == null) {
            LOGGER.warning("Skipping this unsupported SecurityInfo");
            continue;
        }/*from w w  w  .j a  va 2 s  .c  om*/
        securityInfos.add(securityInfo);
    }
}