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

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

Introduction

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

Prototype

ASN1ObjectIdentifier BasicConstraints

To view the source code for org.bouncycastle.asn1.x509 X509Extensions BasicConstraints.

Click Source Link

Document

Basic Constraints

Usage

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;//w ww.  jav  a 2  s  .c o m
    DERObjectIdentifier oid;
    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.globus.security.util.CertificateUtil.java

License:Apache License

/**
 * Return CA Path constraint//from  ww  w  .j  ava  2  s  .  c  om
 *
 * @param crt
 * @return
 * @throws IOException
 */
public static int getCAPathConstraint(TBSCertificateStructure crt) throws IOException {

    X509Extensions extensions = crt.getExtensions();
    if (extensions == null) {
        return -1;
    }
    X509Extension proxyExtension = extensions.getExtension(X509Extensions.BasicConstraints);
    if (proxyExtension != null) {
        BasicConstraints basicExt = getBasicConstraints(proxyExtension);
        if (basicExt.isCA()) {
            BigInteger pathLen = basicExt.getPathLenConstraint();
            return (pathLen == null) ? Integer.MAX_VALUE : pathLen.intValue();
        } else {
            return -1;
        }
    }
    return -1;
}

From source file:org.globus.security.util.CertificateUtil.java

License:Apache License

/**
 * Returns certificate type of the given TBS certificate. <BR> The
 * certificate type is {@link org.globus.security.Constants.CertificateType#CA
 * CertificateType.CA} <B>only</B> if the certificate contains a
 * BasicConstraints extension and it is marked as CA.<BR> A certificate is a
 * GSI-2 proxy when the subject DN of the certificate ends with
 * <I>"CN=proxy"</I> (certificate type {@link org.globus.security.Constants.CertificateType#GSI_2_PROXY
 * CertificateType.GSI_2_PROXY}) or <I>"CN=limited proxy"</I> (certificate
 * type {@link org.globus.security.Constants.CertificateType#GSI_2_LIMITED_PROXY
 * CertificateType.LIMITED_PROXY}) component and the issuer DN of the
 * certificate matches the subject DN without the last proxy <I>CN</I>
 * component.<BR> A certificate is a GSI-3 proxy when the subject DN of the
 * certificate ends with a <I>CN</I> component, the issuer DN of the
 * certificate matches the subject DN without the last <I>CN</I> component
 * and the certificate contains {@link org.globus.security.proxyExtension.ProxyCertInfo
 * ProxyCertInfo} critical extension. The certificate type is {@link
 * org.globus.security.Constants.CertificateType#GSI_3_IMPERSONATION_PROXY
 * CertificateType.GSI_3_IMPERSONATION_PROXY} if the policy language of the
 * {@link org.globus.security.proxyExtension.ProxyCertInfo ProxyCertInfo}
 * extension is set to {@link org.globus.security.proxyExtension.ProxyPolicy#IMPERSONATION
 * ProxyPolicy.IMPERSONATION} OID. The certificate type is {@link
 * org.globus.security.Constants.CertificateType#GSI_3_LIMITED_PROXY
 * CertificateType.GSI_3_LIMITED_PROXY} if the policy language of the {@link
 * org.globus.security.proxyExtension.ProxyCertInfo ProxyCertInfo} extension
 * is set to {@link org.globus.security.proxyExtension.ProxyPolicy#LIMITED
 * ProxyPolicy.LIMITED} OID. The certificate type is {@link
 * org.globus.security.Constants.CertificateType#GSI_3_INDEPENDENT_PROXY
 * CertificateType.GSI_3_INDEPENDENT_PROXY} if the policy language of the
 * {@link org.globus.security.proxyExtension.ProxyCertInfo ProxyCertInfo}
 * extension is set to {@link org.globus.security.proxyExtension.ProxyPolicy#INDEPENDENT
 * ProxyPolicy.INDEPENDENT} OID. The certificate type is {@link
 * org.globus.security.Constants.CertificateType#GSI_3_RESTRICTED_PROXY
 * CertificateType.GSI_3_RESTRICTED_PROXY} if the policy language of the
 * {@link org.globus.security.proxyExtension.ProxyCertInfo ProxyCertInfo}
 * extension is set to any other OID then the above.<BR> The certificate
 * type is {@link org.globus.security.Constants.CertificateType#EEC
 * CertificateType.EEC} if the certificate is not a CA certificate or a
 * GSI-2 or GSI-3 proxy./*from  w  w w  . ja v a  2s .  c o m*/
 *
 * @param crt the TBS certificate to get the type of.
 * @return the certificate type. The certificate type is determined by rules
 *         described above.
 * @throws java.io.IOException if something goes wrong.
 * @throws java.security.cert.CertificateException
 *                             for proxy certificates, if the issuer DN of
 *                             the certificate does not match the subject DN
 *                             of the certificate without the last <I>CN</I>
 *                             component. Also, for GSI-3 proxies when the
 *                             <code>ProxyCertInfo</code> extension is not
 *                             marked as critical.
 */
public static Constants.CertificateType getCertificateType(TBSCertificateStructure crt)
        throws CertificateException, IOException {

    X509Extensions extensions = crt.getExtensions();
    X509Extension ext = null;

    if (extensions != null) {
        ext = extensions.getExtension(X509Extensions.BasicConstraints);
        if (ext != null) {
            BasicConstraints basicExt = getBasicConstraints(ext);
            if (basicExt.isCA()) {
                return Constants.CertificateType.CA;
            }
        }
    }

    Constants.CertificateType type = Constants.CertificateType.EEC;

    // does not handle multiple AVAs
    X509Name subject = crt.getSubject();

    ASN1Set entry = X509NameHelper.getLastNameEntry(subject);
    ASN1Sequence ava = (ASN1Sequence) entry.getObjectAt(0);
    if (X509Name.CN.equals(ava.getObjectAt(0))) {
        type = processCN(extensions, type, ava);
    }

    return type;
}

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

License:Mozilla Public License

/**
 * Handles the nitty gritty of signing a CSR
 *
 * @param rootCert The certificate of the root authority who will vouch for the entity
 * @param rootPrivKey The private key of the root authority who will vouch for the entity
 * @param csr The entitie's CSR//  www .j  av a2s  .c  o  m
 * @param keyType The type of the key, e.g. "RSA", "DSA"
 * @return A certificate chain as an array of X509Certificate instances or null if an
 * error occurred
 */
private X509Certificate[] createSignedCert(X509Certificate rootCert, PrivateKey rootPrivKey,
        PKCS10CertificationRequest csr, String keyType) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    try {
        Date validFrom = new Date();
        validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000));
        Date validTo = new Date();
        validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000)));

        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(rootCert.getSubjectX500Principal());
        certGen.setNotBefore(validFrom);
        certGen.setNotAfter(validTo);
        certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
        certGen.setPublicKey(csr.getPublicKey("BC"));

        if (keyType.toLowerCase().equals("rsa"))
            certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
        if (keyType.toLowerCase().equals("dsa"))
            certGen.setSignatureAlgorithm("DSAWithSHA1");

        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(rootCert));
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
        certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));

        X509Certificate issuedCert = certGen.generate(rootPrivKey, "BC");
        return new X509Certificate[] { issuedCert, rootCert };
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:org.jcryptool.visual.jctca.Util.java

License:Open Source License

public static X509Certificate certificateForKeyPair(String principal, String country, String street, String zip,
        String city, String unit, String organisation, String mail, PublicKey pub, PrivateKey priv,
        BigInteger serialNumber, X509Certificate caCert, Date expiryDate, Date startDate, PrivateKey caKey) {
    try {// w ww . jav  a  2  s . c  om
        KeyPair keyPair = new KeyPair(pub, priv); // public/private key pair
                                                  // that we are creating
                                                  // certificate for

        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        X509Name subjectName = new X509Name("CN=" + principal + ", " + //$NON-NLS-1$ //$NON-NLS-2$
                "ST=" + street + ", " + //$NON-NLS-1$ //$NON-NLS-2$
                "L=" + zip + " " + city + ", " + "C=" + country + ", " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
                "OU=" + unit + ", " + //$NON-NLS-1$ //$NON-NLS-2$
                "O=" + organisation + ", " + //$NON-NLS-1$ //$NON-NLS-2$
                "E=" + mail); //$NON-NLS-1$

        certGen.setSerialNumber(serialNumber);
        if (caCert != null) {
            certGen.setIssuerDN(caCert.getSubjectX500Principal());
            certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                    new AuthorityKeyIdentifierStructure(caCert));
            // FIXME not working any more with BouncyCastle 1.51
            //                certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(
            //                        keyPair.getPublic()));
        } else {
            certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
            certGen.addExtension(X509Extensions.KeyUsage, true,
                    new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
            certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
                    new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
        }
        certGen.setNotBefore(startDate);
        certGen.setNotAfter(expiryDate);
        certGen.setSubjectDN(subjectName);
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA512withRSA");//$NON-NLS-1$

        X509Certificate cert;

        cert = certGen.generate(caKey, "BC");//$NON-NLS-1$
        return cert;
    } catch (CertificateEncodingException e) {
        LogUtil.logError(e);
    } catch (InvalidKeyException e) {
        LogUtil.logError(e);
    } catch (IllegalStateException e) {
        LogUtil.logError(e);
    } catch (NoSuchProviderException e) {
        LogUtil.logError(e);
    } catch (NoSuchAlgorithmException e) {
        LogUtil.logError(e);
    } catch (SignatureException e) {
        LogUtil.logError(e);
    } catch (CertificateParsingException e) {
        LogUtil.logError(e);
    }

    return null;

    // note: private key of CA
}

From source file:org.kopi.ebics.certificate.X509Generator.java

License:Open Source License

/**
 * Returns an <code>X509Certificate</code> from a given
 * <code>KeyPair</code> and limit dates validations
 * @param keypair the given key pair//from ww  w . j a v  a 2s  .co  m
 * @param issuer the certificate issuer
 * @param notBefore the begin validity date
 * @param notAfter the end validity date
 * @param keyusage the certificate key usage
 * @return the X509 certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
public X509Certificate generate(KeyPair keypair, String issuer, Date notBefore, Date notAfter, int keyusage)
        throws GeneralSecurityException, IOException {
    X509V3CertificateGenerator generator;
    BigInteger serial;
    X509Certificate certificate;
    ASN1EncodableVector vector;

    serial = BigInteger.valueOf(generateSerial());
    generator = new X509V3CertificateGenerator();
    generator.setSerialNumber(serial);
    generator.setIssuerDN(new X509Principal(issuer));
    generator.setNotBefore(notBefore);
    generator.setNotAfter(notAfter);
    generator.setSubjectDN(new X509Principal(issuer));
    generator.setPublicKey(keypair.getPublic());
    generator.setSignatureAlgorithm(X509Constants.SIGNATURE_ALGORITHM);
    generator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));
    generator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            getSubjectKeyIdentifier(keypair.getPublic()));
    generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            getAuthorityKeyIdentifier(keypair.getPublic(), issuer, serial));
    vector = new ASN1EncodableVector();
    vector.add(KeyPurposeId.id_kp_emailProtection);

    generator.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(new DERSequence(vector)));

    switch (keyusage) {
    case X509Constants.SIGNATURE_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.nonRepudiation));
        break;
    case X509Constants.AUTHENTICATION_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.digitalSignature));
        break;
    case X509Constants.ENCRYPTION_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyAgreement));
        break;
    default:
        generator.addExtension(X509Extensions.KeyUsage, false,
                new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        break;
    }

    certificate = generator.generate(keypair.getPrivate(), "BC", new SecureRandom());
    certificate.checkValidity(new Date());
    certificate.verify(keypair.getPublic());

    return certificate;
}

From source file:org.mailster.core.crypto.CertificateUtilities.java

License:Open Source License

/**
 * Generate a CA Root certificate.//from w  ww . ja  v a  2 s .  c o m
 */
private static X509Certificate generateRootCert(String DN, KeyPair pair) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setIssuerDN(new X509Name(true, X509Name.DefaultLookUp, DN));
    certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN));

    setSerialNumberAndValidityPeriod(certGen, true, DEFAULT_VALIDITY_PERIOD);

    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(
            new GeneralNames(new GeneralName(new X509Name(true, X509Name.DefaultLookUp, DN))), BigInteger.ONE));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(pair.getPublic()));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.nonRepudiation));
    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(
            NetscapeCertType.smimeCA | NetscapeCertType.sslCA | NetscapeCertType.objectSigning));

    return certGen.generate(pair.getPrivate(), "BC");
}

From source file:org.mailster.core.crypto.CertificateUtilities.java

License:Open Source License

/**
 * Generate a sample V3 certificate to use as an intermediate or end entity 
 * certificate depending on the <code>isEndEntity</code> argument.
 *//*from w  ww  .j a v a  2  s  . c  om*/
private static X509Certificate generateV3Certificate(String DN, boolean isEndEntity, PublicKey entityKey,
        PrivateKey caKey, X509Certificate caCert) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN));

    setSerialNumberAndValidityPeriod(certGen, false, DEFAULT_VALIDITY_PERIOD);

    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifier(caCert.getEncoded(),
                    new GeneralNames(new GeneralName(
                            new X509Name(true, X509Name.DefaultLookUp, caCert.getSubjectDN().getName()))),
                    caCert.getSerialNumber()));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(entityKey));

    if (isEndEntity) {
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    } else {
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
    }
    return certGen.generate(caKey, "BC");
}

From source file:org.mailster.core.crypto.MailsterKeyStoreFactory.java

License:Open Source License

private void generateSSLServerCertificate(KeyStore store, X500PrivateCredential rootCredential)
        throws Exception {
    LOG.info("Generating SSL server certificate ...");
    KeyPair pair = CertificateUtilities.generateRSAKeyPair(getCryptoStrength());
    String DN = "CN=localhost, " + DN_ROOT;
    X509V3CertificateGenerator v3CertGen = CertificateUtilities.initCertificateGenerator(pair,
            rootCredential.getCertificate().getSubjectX500Principal().getName(), DN, false,
            CertificateUtilities.DEFAULT_VALIDITY_PERIOD);

    v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
            new NetscapeCertType(NetscapeCertType.sslServer | NetscapeCertType.sslClient));

    // Firefox 2 disallows these extensions in an SSL server cert. IE7 doesn't care.
    // v3CertGen.addExtension(X509Extensions.KeyUsage,
    // true, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.keyAgreement |
    // KeyUsage.keyEncipherment));

    Vector<KeyPurposeId> typicalSSLServerExtendedKeyUsages = new Vector<KeyPurposeId>();

    typicalSSLServerExtendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    typicalSSLServerExtendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(typicalSSLServerExtendedKeyUsages));

    X509Certificate publicKeyCertificate = v3CertGen.generate(pair.getPrivate());
    store.setKeyEntry(MAILSTER_SSL_ALIAS, pair.getPrivate(), KEYSTORE_PASSWORD,
            new Certificate[] { publicKeyCertificate, rootCredential.getCertificate() });
    CertificateUtilities.exportCertificate(publicKeyCertificate, SSL_CERT_FULL_PATH, false);
}

From source file:org.mailster.core.crypto.MailsterKeyStoreFactory.java

License:Open Source License

private void generateDummySSLClientCertificate(KeyStore ks) throws Exception {
    LOG.info("Generating a Dummy SSL client certificate ...");
    KeyPair pair = CertificateUtilities.generateRSAKeyPair(getCryptoStrength());
    String DN = "CN=SSL dummy client cert, O=Dummy org., C=FR";
    X509V3CertificateGenerator v3CertGen = CertificateUtilities.initCertificateGenerator(pair, DN, DN, true,
            CertificateUtilities.DEFAULT_VALIDITY_PERIOD);

    v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
            new NetscapeCertType(NetscapeCertType.sslClient));

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));

    X509Certificate cert = v3CertGen.generate(pair.getPrivate());
    ks.setKeyEntry(DUMMY_SSL_CLIENT_ALIAS, pair.getPrivate(), KEYSTORE_PASSWORD, new Certificate[] { cert });
}