Example usage for org.bouncycastle.asn1.x509 X509Extensions oids

List of usage examples for org.bouncycastle.asn1.x509 X509Extensions oids

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 X509Extensions oids.

Prototype

public Enumeration oids() 

Source Link

Document

return an Enumeration of the extension field's object ids.

Usage

From source file:org.glite.voms.PKIVerifier.java

License:Open Source License

/**
 * Verifies an Attribute Certificate according to RFC 3281.
 * //from w  ww. j a  v a 2  s  .c om
 * @param ac
 *            the Attribute Certificate to verify.
 * 
 * @return true if the attribute certificate is verified, false otherwise.
 */
public boolean verify(AttributeCertificate ac) {

    if (ac == null || vomsStore == null)
        return false;

    AttributeCertificateInfo aci = ac.getAcinfo();
    X509Certificate[] certificates = null;

    ACCerts certList = aci.getCertList();

    LSCFile lsc = null;
    String voName = ac.getVO();

    if (certList != null)
        lsc = vomsStore.getLSC(voName, ac.getHost());

    logger.debug("LSC is: " + lsc);
    if (lsc != null) {
        boolean success = false;
        Vector dns = lsc.getDNLists();
        Iterator dnIter = dns.iterator();

        // First verify if LSC file applies;

        while (!success && dnIter.hasNext()) {
            boolean doBreak = false;

            while (dnIter.hasNext() && !doBreak) {
                Iterator certIter = certList.getCerts().iterator();
                Vector realDNs = (Vector) dnIter.next();
                Iterator realDNsIter = realDNs.iterator();

                while (realDNsIter.hasNext() && certIter.hasNext() && !doBreak) {
                    String dn = null;
                    String is = null;

                    try {
                        dn = (String) realDNsIter.next();
                        is = (String) realDNsIter.next();
                    } catch (NoSuchElementException e) {
                        doBreak = true;
                    }
                    X509Certificate cert = (X509Certificate) certIter.next();
                    String candidateDN = PKIUtils.getOpenSSLFormatPrincipal(cert.getSubjectDN());
                    String candidateIs = PKIUtils.getOpenSSLFormatPrincipal(cert.getIssuerDN());

                    logger.debug("dn is : " + dn);
                    logger.debug("is is : " + is);
                    logger.debug("canddn is : " + candidateDN);
                    logger.debug("candis is : " + candidateIs);
                    logger.debug("dn == canddn is " + dn.equals(candidateDN));
                    logger.debug("is == candis is " + is.equals(candidateIs));
                    if (!dn.equals(candidateDN) || !is.equals(candidateIs))
                        doBreak = true;
                }

                if (!doBreak && !realDNsIter.hasNext() && !certIter.hasNext())
                    success = true;
            }
        }

        if (success == true) {
            // LSC found. Now verifying certificate
            certificates = (X509Certificate[]) certList.getCerts().toArray(new X509Certificate[] {});
        }
    }

    if (certificates == null) {
        // lsc check failed
        logger.debug("lsc check failed.");
        // System.out.println("Looking for certificates.");
        if (logger.isDebugEnabled())
            logger.debug("Looking for hash: " + PKIUtils.getHash(ac.getIssuer()) + " for certificate: "
                    + ac.getIssuer().getName());

        X509Certificate[] candidates = vomsStore.getAACandidate(ac.getIssuer(), voName);

        if (candidates == null)
            logger.debug("No candidates found!");
        else if (candidates.length != 0) {
            int i = 0;
            while (i < candidates.length) {
                X509Certificate currentCert = (X509Certificate) candidates[i];
                PublicKey key = currentCert.getPublicKey();

                if (logger.isDebugEnabled()) {
                    logger.debug("Candidate: " + currentCert.getSubjectDN().getName());
                    logger.debug("Key class: " + key.getClass());
                    logger.debug("Key: " + key);
                    byte[] data = key.getEncoded();
                    String str = "Key: ";

                    for (int j = 0; j < data.length; j++)
                        str += Integer.toHexString(data[j]) + " ";

                    logger.debug(str);
                }

                if (ac.verifyCert(currentCert)) {
                    logger.debug("Signature Verification OK");

                    certificates = new X509Certificate[1];
                    certificates[0] = currentCert;
                    break;
                } else {
                    logger.debug("Signature Verification false");
                }
                i++;
            }
        }
    }

    if (certificates == null) {
        logger.error(
                "Cannot find usable certificates to validate the AC. Check that the voms server host certificate is in your vomsdir directory.");
        return false;
    }

    if (logger.isDebugEnabled()) {
        for (int l = 0; l < certificates.length; l++)
            logger.debug("Position: " + l + " value: " + certificates[l].getSubjectDN().getName());
    }

    if (!verify(certificates)) {
        logger.error("Cannot verify issuer certificate chain for AC");
        return false;
    }

    if (!ac.isValid()) {
        logger.error("Attribute Certificate not valid at current time.");
        return false;
    }

    // AC Targeting verification

    ACTargets targets = aci.getTargets();

    if (targets != null) {
        String hostname = getHostName();

        boolean success = false;
        Iterator i = targets.getTargets().iterator();

        while (i.hasNext()) {
            String name = (String) i.next();

            if (name.equals(hostname)) {
                success = true;
                break;
            }
        }
        if (!success) {
            logger.error("Targeting check failed!");
            return false;
        }
    }

    // unhandled extensions check
    X509Extensions exts = aci.getExtensions();

    if (exts != null) {
        Enumeration oids = exts.oids();
        while (oids.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) oids.nextElement();
            X509Extension ext = exts.getExtension(oid);
            if (ext.isCritical() && !handledACOIDs.contains(oid)) {
                logger.error("Unknown critical extension discovered: " + oid.getId());
                return false;
            }
        }
    }
    return true;
}

From source file:org.globus.gsi.trustmanager.X509ProxyCertPathValidator.java

License:Apache License

@SuppressWarnings("unused")
protected void checkProxyConstraints(TBSCertificateStructure proxy, TBSCertificateStructure issuer,
        X509Certificate checkedProxy) throws CertPathValidatorException, IOException {

    X509Extensions extensions;
    ASN1ObjectIdentifier oid;/*  w  ww  . j  a v a  2  s.  c  om*/
    X509Extension proxyExtension;

    X509Extension proxyKeyUsage = null;

    extensions = proxy.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (ASN1ObjectIdentifier) e.nextElement();
            proxyExtension = extensions.getExtension(oid);
            if (oid.equals(X509Extension.subjectAlternativeName)
                    || oid.equals(X509Extension.issuerAlternativeName)) {
                // No Alt name extensions - 3.2 & 3.5
                throw new CertPathValidatorException("Proxy violation: no Subject or Issuer Alternative Name");
            } else if (oid.equals(X509Extension.basicConstraints)) {
                // Basic Constraint must not be true - 3.8
                BasicConstraints basicExt = CertificateUtil.getBasicConstraints(proxyExtension);
                if (basicExt.isCA()) {
                    throw new CertPathValidatorException("Proxy violation: Basic Constraint CA is set to true");
                }
            } else if (oid.equals(X509Extension.keyUsage)) {
                proxyKeyUsage = proxyExtension;

                checkKeyUsage(issuer, proxyExtension);
            }
        }
    }

    extensions = issuer.getExtensions();

    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (ASN1ObjectIdentifier) e.nextElement();
            proxyExtension = extensions.getExtension(oid);
            checkExtension(oid, proxyExtension, proxyKeyUsage);
        }
    }

}

From source file:org.globus.security.trustmanager.X509ProxyCertPathValidator.java

License:Apache License

@SuppressWarnings("unused")
protected void checkProxyConstraints(TBSCertificateStructure proxy, TBSCertificateStructure issuer,
        X509Certificate checkedProxy) throws CertPathValidatorException, IOException {

    X509Extensions extensions;
    DERObjectIdentifier oid;// ww  w  .ja  va2  s .  c om
    X509Extension proxyExtension;

    X509Extension proxyKeyUsage = null;

    extensions = proxy.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (DERObjectIdentifier) e.nextElement();
            proxyExtension = extensions.getExtension(oid);
            if (oid.equals(X509Extensions.SubjectAlternativeName)
                    || oid.equals(X509Extensions.IssuerAlternativeName)) {
                // No Alt name extensions - 3.2 & 3.5
                throw new CertPathValidatorException("Proxy violation: no Subject or Issuer Alternative Name");
            } else if (oid.equals(X509Extensions.BasicConstraints)) {
                // Basic Constraint must not be true - 3.8
                BasicConstraints basicExt = CertificateUtil.getBasicConstraints(proxyExtension);
                if (basicExt.isCA()) {
                    throw new CertPathValidatorException("Proxy violation: Basic Constraint CA is set to true");
                }
            } else if (oid.equals(X509Extensions.KeyUsage)) {
                proxyKeyUsage = proxyExtension;

                checkKeyUsage(issuer, proxyExtension);
            }
        }
    }

    extensions = issuer.getExtensions();

    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (DERObjectIdentifier) e.nextElement();
            proxyExtension = extensions.getExtension(oid);
            checkExtension(oid, proxyExtension, proxyKeyUsage);
        }
    }

}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

License:Open Source License

protected X509Certificate createCertificateFromCSR(PKCS10CertificationRequest csr) throws CertException {
    X509Certificate cert;//from w ww.ja va 2s  .c  om
    try {
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(getRootCertificate().getIssuerX500Principal());
        certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
        certGen.setNotBefore(getCertStartDate());
        certGen.setNotAfter(getCertEndDate());
        certGen.setPublicKey(csr.getPublicKey("BC"));
        certGen.setSignatureAlgorithm(CERT_SIGNATURE_ALGORITHM);
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(getRootCertificate()));
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
        certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

        ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes();
        for (int i = 0; i != attributes.size(); i++) {
            Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));
            if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));
                @SuppressWarnings("rawtypes")
                Enumeration e = extensions.oids();
                while (e.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                    X509Extension ext = extensions.getExtension(oid);
                    certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
                }
            }
        }

        KeyPair rootKeyPair = getKeyPair(rootService.getRootKeyStore(), rootService.getRootKeyAlias(),
                rootService.getRootCertificateAlias(), rootService.getRootKeyPassword());
        cert = certGen.generate(rootKeyPair.getPrivate(), "BC");
    } catch (CertificateParsingException e) {
        throw new CertException(e);
    } catch (CertificateEncodingException e) {
        throw new CertException(e);
    } catch (InvalidKeyException e) {
        throw new CertException(e);
    } catch (IllegalStateException e) {
        throw new CertException(e);
    } catch (NoSuchProviderException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (java.security.SignatureException e) {
        throw new CertException(e);
    }
    LOG.debug("Certificate generated for subject: " + cert.getSubjectDN());
    return cert;
}

From source file:org.qipki.crypto.x509.X509ExtensionsReaderImpl.java

License:Open Source License

@Override
public List<X509ExtensionHolder> extractRequestedExtensions(PKCS10CertificationRequest pkcs10) {
    final List<X509ExtensionHolder> extractedExtensions = new ArrayList<X509ExtensionHolder>();
    final CertificationRequestInfo certificationRequestInfo = pkcs10.getCertificationRequestInfo();
    final ASN1Set attributesAsn1Set = certificationRequestInfo.getAttributes();
    if (attributesAsn1Set == null) {
        return extractedExtensions;
    }/*from w  w  w . j  a v a2 s. c om*/
    // The `Extension Request` attribute is contained within an ASN.1 Set,
    // usually as the first element.
    X509Extensions requestedExtensions = null;
    for (int i = 0; i < attributesAsn1Set.size(); ++i) {
        // There should be only only one attribute in the set. (that is, only
        // the `Extension Request`, but loop through to find it properly)
        final DEREncodable derEncodable = attributesAsn1Set.getObjectAt(i);
        if (derEncodable instanceof DERSequence) {
            final Attribute attribute = new Attribute((DERSequence) attributesAsn1Set.getObjectAt(i));

            if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                // The `Extension Request` attribute is present.
                final ASN1Set attributeValues = attribute.getAttrValues();

                // The X509Extensions are contained as a value of the ASN.1 Set.
                // WARN Assuming that it is the first value of the set.
                if (attributeValues.size() >= 1) {
                    DEREncodable extensionsDEREncodable = attributeValues.getObjectAt(0);
                    ASN1Sequence extensionsASN1Sequence = (ASN1Sequence) extensionsDEREncodable;
                    requestedExtensions = new X509Extensions(extensionsASN1Sequence);
                    // No need to search any more.
                    break;
                }
            }
        }
    }
    if (requestedExtensions != null) {
        Enumeration<?> e = requestedExtensions.oids();
        while (e.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
            X509Extension extension = requestedExtensions.getExtension(oid);
            extractedExtensions.add(new X509ExtensionHolder(oid, extension.isCritical(),
                    X509Extension.convertValueToObject(extension)));
        }
    }
    return extractedExtensions;
}

From source file:org.votingsystem.signature.util.CertUtils.java

License:Open Source License

/**
 * Generate V3 Certificate from CSR//from w ww  .  j  a v  a  2 s.com
 */
public static X509Certificate generateV3EndEntityCertFromCsr(PKCS10CertificationRequest csr, PrivateKey caKey,
        X509Certificate caCert, Date dateBegin, Date dateFinish, String strSubjectDN,
        DERTaggedObject... certExtensions) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    PublicKey requestPublicKey = csr.getPublicKey();
    X509Principal x509Principal = new X509Principal(strSubjectDN);
    certGen.setSerialNumber(KeyGeneratorVS.INSTANCE.getSerno());
    log.info("generateV3EndEntityCertFromCsr - SubjectX500Principal(): " + caCert.getSubjectX500Principal());
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(dateBegin);
    certGen.setNotAfter(dateFinish);
    certGen.setSubjectDN(x509Principal);
    certGen.setPublicKey(requestPublicKey);
    certGen.setSignatureAlgorithm(ContextVS.CERT_GENERATION_SIG_ALGORITHM);
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(requestPublicKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));//Certificado final
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes();
    if (attributes != null) {
        for (int i = 0; i != attributes.size(); i++) {
            if (attributes.getObjectAt(i) instanceof DERTaggedObject) {
                DERTaggedObject taggedObject = (DERTaggedObject) attributes.getObjectAt(i);
                ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(
                        ContextVS.VOTING_SYSTEM_BASE_OID + taggedObject.getTagNo());
                certGen.addExtension(oid, true, taggedObject);
            } else {
                Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));
                if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                    X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));
                    Enumeration e = extensions.oids();
                    while (e.hasMoreElements()) {
                        DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                        X509Extension ext = extensions.getExtension(oid);
                        certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
                    }
                }
            }
        }
    }
    if (certExtensions != null) {
        for (DERTaggedObject taggedObject : certExtensions) {
            if (taggedObject != null) {
                ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(
                        ContextVS.VOTING_SYSTEM_BASE_OID + taggedObject.getTagNo());
                certGen.addExtension(oid, true, taggedObject);
            }
            log.log(Level.FINE, "null taggedObject");
        }
    }
    X509Certificate cert = certGen.generate(caKey, ContextVS.PROVIDER);
    cert.verify(caCert.getPublicKey());
    return cert;
}

From source file:test.be.fedict.eid.applet.PcscTest.java

License:Open Source License

@Test
public void testBeIDPKIValidationCRLOnly() throws Exception {
    PcscEid pcscEid = new PcscEid(new TestView(), this.messages);
    if (false == pcscEid.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEid.waitForEidPresent();//  w  w  w . ja  v a2s.  com
    }

    List<X509Certificate> certChain;
    try {
        certChain = pcscEid.getSignCertificateChain();
    } finally {
        pcscEid.close();
    }
    LOG.debug("certificate: " + certChain.get(0));

    NetworkConfig networkConfig = new NetworkConfig("proxy.yourict.net", 8080);

    MemoryCertificateRepository memoryCertificateRepository = new MemoryCertificateRepository();
    X509Certificate rootCaCertificate = loadCertificate("be/fedict/trust/belgiumrca.crt");
    memoryCertificateRepository.addTrustPoint(rootCaCertificate);
    X509Certificate rootCa2Certificate = loadCertificate("be/fedict/trust/belgiumrca2.crt");
    memoryCertificateRepository.addTrustPoint(rootCa2Certificate);

    RevocationData revocationData = new RevocationData();
    TrustValidator trustValidator = new TrustValidator(memoryCertificateRepository);
    trustValidator.setRevocationData(revocationData);

    trustValidator.addTrustLinker(new PublicKeyTrustLinker());
    OnlineCrlRepository crlRepository = new OnlineCrlRepository(networkConfig);
    trustValidator.addTrustLinker(new CrlTrustLinker(crlRepository));

    try {
        trustValidator.isTrusted(certChain);
    } catch (Exception e) {
        LOG.warn("error: " + e.getMessage());
    }

    byte[] crlData = revocationData.getCrlRevocationData().get(1).getData();
    CertificateList certificateList = CertificateList.getInstance(new ASN1InputStream(crlData).readObject());
    X509Extensions crlExtensions = certificateList.getTBSCertList().getExtensions();
    Enumeration<DERObjectIdentifier> oids = crlExtensions.oids();
    while (oids.hasMoreElements()) {
        LOG.debug("oid type: " + oids.nextElement().getId());
    }
}