Example usage for org.bouncycastle.asn1 DERSequence getObjectAt

List of usage examples for org.bouncycastle.asn1 DERSequence getObjectAt

Introduction

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

Prototype

public ASN1Encodable getObjectAt(int index) 

Source Link

Document

Return the object at the sequence position indicated by index.

Usage

From source file:br.gov.frameworkdemoiselle.certificate.oid.OIDGeneric.java

License:Open Source License

/**
 * Instance for object.//from w  w w  . j a va2s.  c  o m
 *
 * @param data -> byte array with certificate content.
 * @return Object GenericOID
 * @throws IOException
 * @throws Exception
 */
public static OIDGeneric getInstance(byte[] data) throws IOException, Exception {
    ASN1InputStream is = new ASN1InputStream(data);
    DERSequence sequence = (DERSequence) is.readObject();
    DERObjectIdentifier objectIdentifier = (DERObjectIdentifier) sequence.getObjectAt(0);
    DERTaggedObject tag = (DERTaggedObject) sequence.getObjectAt(1);
    DEROctetString octetString = null;
    DERPrintableString printableString = null;
    DERUTF8String utf8String = null;
    DERIA5String ia5String = null;

    try {
        octetString = (DEROctetString) DEROctetString.getInstance(tag);
    } catch (Exception ex) {
        try {
            printableString = DERPrintableString.getInstance(tag);
        } catch (Exception e1) {
            try {
                utf8String = DERUTF8String.getInstance(tag);
            } catch (Exception e2) {
                ia5String = DERIA5String.getInstance(tag);
            }
        }
    }

    String className = "br.gov.frameworkdemoiselle.certificate.oid.OID_"
            + objectIdentifier.getId().replaceAll("[.]", "_");
    OIDGeneric oidGenerico;
    try {
        oidGenerico = (OIDGeneric) Class.forName(className).newInstance();
    } catch (InstantiationException e) {
        throw new Exception("Can not instace class '" + className + "'.", e);
    } catch (IllegalAccessException e) {
        throw new Exception("Was not possible instace class '" + className + "'.", e);
    } catch (ClassNotFoundException e) {
        oidGenerico = new OIDGeneric();
    }

    oidGenerico.setOid(objectIdentifier.getId());

    if (octetString != null) {
        oidGenerico.setData(new String(octetString.getOctets()));
    } else if (printableString != null) {
        oidGenerico.setData(printableString.getString());
    } else if (utf8String != null) {
        oidGenerico.setData(utf8String.getString());
    } else {
        oidGenerico.setData(ia5String.getString());
    }
    oidGenerico.initialize();
    return oidGenerico;
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.CAdESSigner.java

License:Open Source License

/**
 * A validao se basea apenas em assinaturas com um assinante apenas.
 * Valida apenas com o contedo do tipo DATA: OID ContentType
 * 1.2.840.113549.1.9.3 = OID Data 1.2.840.113549.1.7.1
 *
 * @param content/*from w w w  .j a v  a2 s.co  m*/
 * @param signed
 * @return
 * @params content Necessrio informar apenas se o pacote PKCS7 NO for do
 * tipo ATTACHED. Caso seja do tipo attached, este parmetro ser
 * substituido pelo contedo do pacote PKCS7.
 * @params signed Valor em bytes do pacote PKCS7, como por exemplo o
 * contedo de um arquivo ".p7s". No  a assinatura pura como no caso do
 * PKCS1. TODO: Implementar validao de co-assinaturas
 */
@Override
public boolean check(byte[] content, byte[] signed) {

    CMSSignedData signedData = null;
    PublicKey publicKey = null;

    try {
        if (content == null) {
            signedData = new CMSSignedData(signed);
        } else {
            signedData = new CMSSignedData(new CMSProcessableByteArray(content), signed);
        }
    } catch (CMSException exception) {
        throw new SignerException("Invalid bytes for a PKCS7 package", exception);
    }

    SignerInformationStore signerInformationStore = signedData.getSignerInfos();
    SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator()
            .next();

    /*
     * Retirando o Certificado Digital e a chave Pblica da assinatura
     */
    try {
        CertStore certs;
        try {
            Security.addProvider(new BouncyCastleProvider());
            certs = signedData.getCertificatesAndCRLs("Collection", "BC");
            Collection<? extends Certificate> collCertificados = certs
                    .getCertificates(signerInformation.getSID());
            if (!collCertificados.isEmpty()) {
                certificate = (X509Certificate) collCertificados.iterator().next();
                publicKey = certificate.getPublicKey();
            }
        } catch (NoSuchAlgorithmException exception) {
            throw new SignerException(exception);
        } catch (NoSuchProviderException exception) {
            throw new SignerException(exception);
        } catch (CMSException exception) {
            throw new SignerException(exception);
        } catch (CertStoreException exception) {
            throw new SignerException(exception);
        }
    } catch (SignerException ex) {
        throw new SignerException(
                "Error on get information about certificates and public keys from a package PKCS7", ex);
    }

    try {
        signerInformation.verify(publicKey, "BC");
    } catch (NoSuchAlgorithmException e) {
        throw new SignerException(e);
    } catch (NoSuchProviderException e) {
        throw new SignerException(e);
    } catch (CMSException e) {
        throw new SignerException("Invalid signature", e);
    }

    AttributeTable signedAttributes = signerInformation.getSignedAttributes();

    if (signedAttributes == null) {
        throw new SignerException("Package PKCS7 without signed attributes");
    }

    // Validar a poltica
    org.bouncycastle.asn1.cms.Attribute signaturePolicyIdentifierAttribute = signedAttributes
            .get(new DERObjectIdentifier((new SignaturePolicyIdentifier()).getOID()));
    if (signaturePolicyIdentifierAttribute != null) {
        ASN1Set valueAttribute = signaturePolicyIdentifierAttribute.getAttrValues();
        for (Enumeration<DERSequence> iterator = valueAttribute.getObjects(); iterator.hasMoreElements();) {
            DERSequence sequence = iterator.nextElement();
            DERObjectIdentifier policyIdentifier = (DERObjectIdentifier) sequence.getObjectAt(0);
            String policyOID = policyIdentifier.getId();
            SignaturePolicy policy = SignaturePolicyFactory.getInstance().factory(policyOID);
            if (policy != null) {
                policy.validate(content, signed);
            } else {
                LOGGER.log(Level.WARNING, "N\u00e3o existe validador para a pol\u00edtica {0}", policyOID);
            }
        }
    } else {
        throw new SignerException("ICP-Brasil invalid format. There is not policy signature.");
    }
    return true;
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.util.ValidadorUtil.java

License:Open Source License

public static void validate(X509Certificate certificate) {
    /*//w w  w  .ja v  a 2s . co m
     * Assinaturas digitais geradas segundo esta Poltica de Assinatura
     * devero ser criadas com chave privada associada ao certificado
     * ICP-Brasil * tipo A1 (do OID 2.16.76.1.2.1.1 ao OID
     * 2.16.76.1.2.1.100), tipo A2 (do OID 2.16.76.1.2.2.1 ao OID
     * 2.16.76.1.2.2.100), do tipo A3 (do OID 2.16.76.1.2.3.1 ao OID
     * 2.16.76.1.2.3.100) e do tipo A4 (do OID 2.16.76.1.2.4.1 ao OID
     * 2.16.76.1.2.4.100), conforme definido em DOC-ICP-04.
     */

    try {
        byte[] val1 = certificate.getExtensionValue("2.5.29.32");
        ASN1InputStream ans1InputStream = new ASN1InputStream(new ByteArrayInputStream(val1));
        DERObject derObject = ans1InputStream.readObject();
        ans1InputStream.close();
        DEROctetString derOctetString = (DEROctetString) derObject;
        byte[] val2 = derOctetString.getOctets();
        ASN1InputStream asn1InputStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
        DERObject derObject2 = asn1InputStream2.readObject();
        asn1InputStream2.close();
        DERSequence derSequence = (DERSequence) derObject2;
        DERSequence derObject3 = (DERSequence) derSequence.getObjectAt(0).getDERObject();
        DERObjectIdentifier objectIdentifier = (DERObjectIdentifier) derObject3.getObjectAt(0);
        String identificador = objectIdentifier.toString();

        if (!(identificador.startsWith("2.16.76.1.2.1.") || identificador.startsWith("2.16.76.1.2.2.")
                || identificador.startsWith("2.16.76.1.2.3.") || identificador.startsWith("2.16.76.1.2.4."))) {
            throw new SignerException("O OID no corresponde a uma Poltica de Certificado.");
        }

        int sufixo = Integer.parseInt(identificador.substring(identificador.lastIndexOf(".") + 1));
        if (sufixo < 1 || sufixo > 100) {
            throw new SignerException("O certificado deve ser do tipo A1, A2, A3 ou A4.");
        }

    } catch (Throwable error) {
        throw new SignerException(
                "A assinaturas digital deve ser criada com chave privada associada ao certificado ICP-Brasil tipo A1, A2, A3 ou A4",
                error);
    }
}

From source file:ch.cyberduck.core.aquaticprime.Receipt.java

License:Open Source License

/**
 * Verifies the App Store Receipt/*from   w ww  . ja  v a 2  s.c  o  m*/
 *
 * @return False if receipt validation failed.
 */
@Override
public boolean verify() {
    try {
        Security.addProvider(new BouncyCastleProvider());
        PKCS7SignedData signature = new PKCS7SignedData(
                IOUtils.toByteArray(new FileInputStream(this.getFile().getAbsolute())));

        signature.verify();
        // For additional security, you may verify the fingerprint of the root CA and the OIDs of the
        // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the
        // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate
        // is (1 2 840 113635 100 6 11 1).

        // Extract the receipt attributes
        CMSSignedData s = new CMSSignedData(new FileInputStream(this.getFile().getAbsolute()));
        CMSProcessable signedContent = s.getSignedContent();
        byte[] originalContent = (byte[]) signedContent.getContent();
        ASN1Object asn = ASN1Object.fromByteArray(originalContent);

        byte[] opaque = null;
        String bundleIdentifier = null;
        String bundleVersion = null;
        byte[] hash = null;

        if (asn instanceof DERSet) {
            // 2 Bundle identifier      Interpret as an ASN.1 UTF8STRING.
            // 3 Application version    Interpret as an ASN.1 UTF8STRING.
            // 4 Opaque value           Interpret as a series of bytes.
            // 5 SHA-1 hash             Interpret as a 20-byte SHA-1 digest value.
            DERSet set = (DERSet) asn;
            Enumeration enumeration = set.getObjects();
            while (enumeration.hasMoreElements()) {
                Object next = enumeration.nextElement();
                if (next instanceof DERSequence) {
                    DERSequence sequence = (DERSequence) next;
                    DEREncodable type = sequence.getObjectAt(0);
                    if (type instanceof DERInteger) {
                        if (((DERInteger) type).getValue().intValue() == 2) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleIdentifier = new String(((DEROctetString) value).getOctets(), "utf-8");
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 3) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleVersion = new String(((DEROctetString) value).getOctets(), "utf-8");
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 4) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                opaque = ((DEROctetString) value).getOctets();
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 5) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                hash = ((DEROctetString) value).getOctets();
                            }
                        }
                    }
                }
            }
        } else {
            log.error(String.format("Expected set of attributes for %s", asn));
            return false;
        }
        if (!StringUtils.equals("ch.sudo.cyberduck", StringUtils.trim(bundleIdentifier))) {
            log.error("Bundle identifier in ASN set does not match");
            return false;
        }
        if (!StringUtils.equals(Preferences.instance().getDefault("CFBundleShortVersionString"),
                StringUtils.trim(bundleVersion))) {
            log.warn("Bundle version in ASN set does not match");
        }

        NetworkInterface en0 = NetworkInterface.getByName("en0");
        if (null == en0) {
            // Interface is not found when link is down #fail
            log.warn("No network interface en0");
        } else {
            byte[] mac = en0.getHardwareAddress();
            if (null == mac) {
                log.error("Cannot determine MAC address");
                // Continue without validation
                return true;
            }
            final String hex = Hex.encodeHexString(mac);
            if (log.isDebugEnabled()) {
                log.debug("Interface en0:" + hex);
            }
            // Compute the hash of the GUID
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(mac);
            digest.update(opaque);
            digest.update(bundleIdentifier.getBytes(Charset.forName("utf-8")));
            byte[] result = digest.digest();
            if (Arrays.equals(result, hash)) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Valid receipt for GUID %s", hex));
                }
                this.name = hex;
            } else {
                log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt",
                        hex));
                return false;
            }
        }
    } catch (Exception e) {
        log.error("Unknown receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    }
    // Always return true to dismiss donation prompt.
    return true;
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

License:Open Source License

String getSubjectAltNameOtherNameUPN() {
    Collection<List<?>> generalNames = null;
    try {//www  .j  av a  2  s .c o m
        generalNames = cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        ZimbraLog.account.warn(LOG_PREFIX + "unable to get subject alternative names", e);
    }

    if (generalNames == null) {
        return null;
    }

    ASN1InputStream decoder = null;
    try {
        // Check that the certificate includes the SubjectAltName extension
        for (List<?> generalName : generalNames) {
            Integer tag = (Integer) generalName.get(0);
            if (GeneralName.otherName == tag.intValue()) {
                // Value is encoded using ASN.1
                decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]);
                DEREncodable encoded = decoder.readObject();
                DERSequence derSeq = (DERSequence) encoded;

                DERObjectIdentifier typeId = DERObjectIdentifier.getInstance(derSeq.getObjectAt(0));
                String oid = typeId.getId();

                String value = null;
                ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1));
                if (OID_UPN.equals(oid)) {
                    ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject());
                    DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject());
                    value = str.getString();
                    return value;
                }
            }
        }
    } catch (IOException e) {
        ZimbraLog.account.warn(LOG_PREFIX + "unable to process ASN.1 data", e);
    } finally {
        ByteUtil.closeStream(decoder);
    }

    return null;
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

License:Open Source License

private void printSubjectAlternativeNames(PrintStream outStream) throws Exception {

    final String UPN_DISPLAY = "Principal Name";
    final String RFC822NAME_DISPLAY = "RFC822 Name";
    final String DNSNAME_DISPLAY = "DNS Name";

    outStream.format("X509v3 Subject Alternative Name: \n");

    ASN1InputStream decoder = null;
    try {//  ww  w  .j a  va 2 s .  c  om
        Collection<List<?>> generalNames = cert.getSubjectAlternativeNames();
        // Check that the certificate includes the SubjectAltName extension
        if (generalNames == null) {
            return;
        }

        /*
           OtherName ::= SEQUENCE {
          type-id    OBJECT IDENTIFIER,
          value      [0] EXPLICIT ANY DEFINED BY type-id }
         */

        for (List<?> generalName : generalNames) {
            Integer tag = (Integer) generalName.get(0);
            if (GeneralName.otherName == tag.intValue()) {
                // Value is encoded using ASN.1
                decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]);
                DEREncodable encoded = decoder.readObject();
                DERSequence derSeq = (DERSequence) encoded;

                DERObjectIdentifier typeId = DERObjectIdentifier.getInstance(derSeq.getObjectAt(0));
                String oid = typeId.getId();

                String value = null;
                ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1));
                if (OID_UPN.equals(oid)) {
                    ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject());
                    DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject());
                    value = str.getString();
                }

                outStream.format("    [%d] %s(%s) = %s\n", tag, oid, UPN_DISPLAY, value);
            } else if (GeneralName.rfc822Name == tag.intValue()) {
                String value = (String) generalName.get(1);
                outStream.format("    [%d] %s = %s\n", tag, RFC822NAME_DISPLAY, value);
            } else if (GeneralName.dNSName == tag.intValue()) {
                String value = (String) generalName.get(1);
                outStream.format("    [%d] %s = %s\n", tag, DNSNAME_DISPLAY, value);
            } else {
                outStream.format("    [%d] - not yet supported\n", tag);
            }

        }
    } catch (CertificateParsingException e) {
        e.printStackTrace();
    } finally {
        ByteUtil.closeStream(decoder);
    }
}

From source file:crossbear.CVRProcessor.java

License:Open Source License

/**
 * Search the "Subject Alternative Name"-field (OID is 2.5.29.17) for Common Names and add all of them as byte[] to a Vector of byte[]s
 * //from  ww  w  .j  a  v  a 2 s  .c  o m
 * @param altNames The DEROctetString found within the "Subject Alternative Name"-Field
 * @param cnBytes The Vector to add all found CNs to
 * @throws IOException
 */
private static void searchAltNamesForCN(DEROctetString altNames, Vector<byte[]> cnBytes) throws IOException {
    DERSequence altNameSequence = (DERSequence) DERSequence.fromByteArray(altNames.getOctets());

    // Look on the type of each element of the sequence
    for (int i = 0; i < altNameSequence.size(); i++) {
        DEREncodable altNameT = altNameSequence.getObjectAt(i);

        // Assert type of the element being a DERTaggedObject
        if (!(altNameT instanceof DERTaggedObject))
            continue;

        // Extract the content of the DERTaggedObject
        DERObject altNameO = ((DERTaggedObject) altNameT).getObject();

        // Assert type of the content being a DEROctetString
        if (!(altNameO instanceof DEROctetString))
            continue;

        // Extract name field and store it
        cnBytes.add(((DEROctetString) altNameO).getEncoded());
    }
}

From source file:crossbear.CVRProcessor.java

License:Open Source License

/**
 * Search a DERSequence for all occurrences of Common Names. They might be stored in the "Subject Alternative Name"-field (OID is 2.5.29.17) or in a commonName-field (OID is 2.5.4.3)
 * /*from  ww w.  ja v a 2  s . c om*/
 * @param seq The sequence to be searched (might be created by calling  DERSequence.fromByteArray(X509Certificate.getEncoded()))
 * @param cnBytes The Vector to add all found CNs to
 * @throws IOException
 */
private static void searchSequenceForCNs(DERSequence seq, Vector<byte[]> cnBytes) throws IOException {

    // Look on the type of each element of the sequence
    for (int i = 0; i < seq.size(); i++) {
        DEREncodable derEncodable = seq.getObjectAt(i);

        // if the type is a DERSequence (i.e. a subsequence) then check if starts with an OID or not
        if (derEncodable instanceof DERSequence) {
            DEREncodable firstSubSequenceElement = ((DERSequence) derEncodable).getObjectAt(0);

            // If it starts with an OID and If the OID is 2.5.29.17 then we found the "Subject Alternative Name"-field
            if ((firstSubSequenceElement instanceof ASN1ObjectIdentifier)
                    && ((ASN1ObjectIdentifier) firstSubSequenceElement).getId().equals("2.5.29.17")) {
                DEREncodable secondSubSequenceElement = ((DERSequence) derEncodable).getObjectAt(1);

                // Assert type of SAN-field being an octetString
                if (secondSubSequenceElement instanceof DEROctetString) {
                    searchAltNamesForCN((DEROctetString) secondSubSequenceElement, cnBytes);
                }

                // If not just continue recursively
            } else {
                searchSequenceForCNs((DERSequence) derEncodable, cnBytes);
            }

            // If the type is a DERSet then we might be close to the CN-Field -> try to extract it
        } else if (derEncodable instanceof DERSet) {
            searchSetForCN((DERSet) derEncodable, cnBytes);

            // If the type is a DERTaggedObject then we might have found the Extension of the certificate
        } else if (derEncodable instanceof DERTaggedObject) {
            int tagno = ((DERTaggedObject) derEncodable).getTagNo();

            // The tag for the extension we are looking for is 3
            if (tagno == 3) {
                DERObject exensionList = ((DERTaggedObject) derEncodable).getObject();

                // Assert type of the extension being a DERSequence
                if (exensionList instanceof DERSequence) {
                    searchSequenceForCNs((DERSequence) exensionList, cnBytes);
                }
            }
        }
    }

}

From source file:crossbear.CVRProcessor.java

License:Open Source License

/**
 * Search a DERSet for Common Names (identified by OID 2.5.4.3) and add all of them as byte[] to a Vector of byte[]s
 * //from   w w  w . ja va  2 s.co m
 * @param set The DERSet to search
 * @param cnBytes The Vector to add all found CNs to
 * @throws IOException
 */
private static void searchSetForCN(DERSet set, Vector<byte[]> cnBytes) throws IOException {

    // The DERSet we are looking for contains exactly one element: a DERSequence
    if (set.size() != 1 || !(set.getObjectAt(0) instanceof DERSequence))
        return;

    // Extract the DERSequence
    DERSequence subseq = (DERSequence) set.getObjectAt(0);

    // The DERSequence we are looking for consists of two elements: an OID and the CN
    // First: Assert type of OID
    if (!(subseq.getObjectAt(0) instanceof ASN1ObjectIdentifier))
        return;

    // Second: Check value of OID to be id-at-commonName
    ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) subseq.getObjectAt(0);
    if (!id.getId().equals("2.5.4.3"))
        return;

    // Third extract the commonName
    cnBytes.add(subseq.getObjectAt(1).getDERObject().getEncoded());
}

From source file:de.fraunhofer.fokus.openeid.ca.AlgorithmIdentifier.java

License:Open Source License

public AlgorithmIdentifier(DERSequence algorithmInfo) {
    DERObjectIdentifier derOid = (DERObjectIdentifier) algorithmInfo.getObjectAt(0);
    algorithmOid = derOid.getId();/*ww w .j av a 2  s.c  om*/
    for (int i = 1; i < algorithmInfo.size(); i++) {
        parameter.add(algorithmInfo.getObjectAt(i));
    }
}