Example usage for org.bouncycastle.asn1.x509 NameConstraints NameConstraints

List of usage examples for org.bouncycastle.asn1.x509 NameConstraints NameConstraints

Introduction

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

Prototype

public NameConstraints(GeneralSubtree[] permitted, GeneralSubtree[] excluded) 

Source Link

Document

Constructor from a given details.

Usage

From source file:com.bettertls.nameconstraints.CertificateGenerator.java

License:Apache License

private void generateCertificatesWithNames(KeyStore rootCa, String commonName, String dnsSan, String ipSan)
        throws Exception {

    GeneralNames sans = null;//from  w  w  w  .  j a v a2  s.co  m
    if (dnsSan != null || ipSan != null) {
        List<GeneralName> generalNames = new ArrayList<>();
        if (dnsSan != null) {
            generalNames.add(new GeneralName(GeneralName.dNSName, dnsSan));
        }
        if (ipSan != null) {
            generalNames.add(new GeneralName(GeneralName.iPAddress, ipSan));
        }
        sans = new GeneralNames(generalNames.toArray(new GeneralName[generalNames.size()]));
    }

    for (String ncIpWhitelist : new String[] { null, ipSubtree, invalidIpSubtree }) {
        for (String ncDnsWhitelist : new String[] { null, hostSubtree, invalidHostSubtree }) {

            List<GeneralSubtree> permittedWhitelist = new ArrayList<>();
            if (ncIpWhitelist != null) {
                permittedWhitelist
                        .add(new GeneralSubtree(new GeneralName(GeneralName.iPAddress, ncIpWhitelist)));
            }
            if (ncDnsWhitelist != null) {
                permittedWhitelist
                        .add(new GeneralSubtree(new GeneralName(GeneralName.dNSName, ncDnsWhitelist)));
            }

            for (String ncIpBlacklist : new String[] { null, ipSubtree, invalidIpSubtree }) {
                for (String ncDnsBlacklist : new String[] { null, hostSubtree, invalidHostSubtree }) {

                    List<GeneralSubtree> permittedBlacklist = new ArrayList<>();
                    if (ncIpBlacklist != null) {
                        permittedBlacklist
                                .add(new GeneralSubtree(new GeneralName(GeneralName.iPAddress, ncIpBlacklist)));
                    }
                    if (ncDnsBlacklist != null) {
                        permittedBlacklist
                                .add(new GeneralSubtree(new GeneralName(GeneralName.dNSName, ncDnsBlacklist)));
                    }

                    NameConstraints nameConstraints = null;
                    if (permittedWhitelist.size() != 0 || permittedBlacklist.size() != 0) {
                        nameConstraints = new NameConstraints(
                                permittedWhitelist.size() == 0 ? null
                                        : permittedWhitelist
                                                .toArray(new GeneralSubtree[permittedWhitelist.size()]),
                                permittedBlacklist.size() == 0 ? null
                                        : permittedBlacklist
                                                .toArray(new GeneralSubtree[permittedBlacklist.size()]));
                    }

                    System.out.println("Generating certificate " + nextCertId + "...");
                    writeCertificateSet(makeTree(nextCertId, rootCa, nameConstraints, commonName, sans),
                            outputDir, Integer.toString(nextCertId));

                    // Build a manifest JSON entry for the certificate
                    JSONArray manifestSans = new JSONArray();
                    if (dnsSan != null) {
                        manifestSans.put(dnsSan);
                    }
                    if (ipSan != null) {
                        manifestSans.put(ipSan);
                    }
                    JSONObject manifestNcs = new JSONObject();
                    JSONArray manifestNcWhitelist = new JSONArray();
                    if (ncDnsWhitelist != null) {
                        manifestNcWhitelist.put(ncDnsWhitelist);
                    }
                    if (ncIpWhitelist != null) {
                        manifestNcWhitelist.put(ncIpWhitelist);
                    }
                    JSONArray manifestNcBlacklist = new JSONArray();
                    if (ncDnsBlacklist != null) {
                        manifestNcBlacklist.put(ncDnsBlacklist);
                    }
                    if (ncIpBlacklist != null) {
                        manifestNcBlacklist.put(ncIpBlacklist);
                    }
                    manifestNcs.put("whitelist", manifestNcWhitelist);
                    manifestNcs.put("blacklist", manifestNcBlacklist);

                    certManifest.put(new JSONObject().put("id", nextCertId).put("commonName", commonName)
                            .put("sans", manifestSans).put("nameConstraints", manifestNcs));

                    nextCertId += 1;
                }
            }
        }
    }
}

From source file:com.integralblue.httpresponsecache.compat.java.security.TestKeyStore.java

License:Apache License

private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey,
        X500Principal subject, X500Principal issuer, int keyUsage, boolean ca,
        List<GeneralName> subjectAltNames, Vector<GeneralSubtree> permittedNameConstraints,
        Vector<GeneralSubtree> excludedNameConstraints) throws Exception {
    // Note that there is no way to programmatically make a
    // Certificate using java.* or javax.* APIs. The
    // CertificateFactory interface assumes you want to read
    // in a stream of bytes, typically the X.509 factory would
    // allow ASN.1 DER encoded bytes and optionally some PEM
    // formats. Here we use Bouncy Castle's
    // X509V3CertificateGenerator and related classes.

    long millisPerDay = 24 * 60 * 60 * 1000;
    long now = System.currentTimeMillis();
    Date start = new Date(now - millisPerDay);
    Date end = new Date(now + millisPerDay);
    BigInteger serial = BigInteger.valueOf(1);

    String keyAlgorithm = privateKey.getAlgorithm();
    String signatureAlgorithm;//from   w  w  w. j  a  v  a 2  s  .  c om
    if (keyAlgorithm.equals("RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else if (keyAlgorithm.equals("DSA")) {
        signatureAlgorithm = "sha1WithDSA";
    } else if (keyAlgorithm.equals("EC")) {
        signatureAlgorithm = "sha1WithECDSA";
    } else if (keyAlgorithm.equals("EC_RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else {
        throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
    }

    X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
    x509cg.setSubjectDN(subject);
    x509cg.setIssuerDN(issuer);
    x509cg.setNotBefore(start);
    x509cg.setNotAfter(end);
    x509cg.setPublicKey(publicKey);
    x509cg.setSignatureAlgorithm(signatureAlgorithm);
    x509cg.setSerialNumber(serial);
    if (keyUsage != 0) {
        x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
    }
    if (ca) {
        x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    }
    for (GeneralName subjectAltName : subjectAltNames) {
        x509cg.addExtension(X509Extensions.SubjectAlternativeName, false,
                new GeneralNames(subjectAltName).getEncoded());
    }
    if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
        x509cg.addExtension(X509Extensions.NameConstraints, true,
                new NameConstraints(permittedNameConstraints, excludedNameConstraints));
    }

    if (privateKey instanceof ECPrivateKey) {
        /*
         * bouncycastle needs its own ECPrivateKey implementation
         */
        KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        privateKey = kf.generatePrivate(ks);
    }
    X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
    if (StandardNames.IS_RI) {
        /*
         * The RI can't handle the BC EC signature algorithm
         * string of "ECDSA", since it expects "...WITHEC...",
         * so convert from BC to RI X509Certificate
         * implementation via bytes.
         */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
        Certificate c = cf.generateCertificate(bais);
        x509c = (X509Certificate) c;
    }
    return x509c;
}

From source file:com.otterca.common.crypto.X509CertificateBuilderImpl.java

License:Apache License

/**
 * Set Name Constraints (RFC3280 4.2.1.11)
 *///www  . j a v  a2  s  .  com
protected void setNameConstraints() {
    // FIXME: add constraints inherited from parent?
    if (!permittedNames.isEmpty() || !excludedNames.isEmpty()) {

        // convert permitted names.
        Vector<org.bouncycastle.asn1.x509.GeneralSubtree> permitted = new Vector<org.bouncycastle.asn1.x509.GeneralSubtree>();
        for (int i = 0; i < permittedNames.size(); i++) {
            GeneralSubtree g = permittedNames.get(i);
            GeneralName name = new GeneralName(new X500Name(g.getName().getName()));
            permitted.add(new org.bouncycastle.asn1.x509.GeneralSubtree(name, g.getMin(), g.getMax()));
        }

        // convert excluded names.
        Vector<org.bouncycastle.asn1.x509.GeneralSubtree> excluded = new Vector<org.bouncycastle.asn1.x509.GeneralSubtree>();
        for (int i = 0; i < excludedNames.size(); i++) {
            GeneralSubtree g = excludedNames.get(i);
            GeneralName name = new GeneralName(new X500Name(g.getName().getName()));
            excluded.add(new org.bouncycastle.asn1.x509.GeneralSubtree(name, g.getMin(), g.getMax()));
        }
        generator.addExtension(X509Extensions.NameConstraints, false, new NameConstraints(permitted, excluded));
    }
}

From source file:net.sf.keystore_explorer.gui.dialogs.extensions.DNameConstraints.java

License:Open Source License

private void okPressed() {
    List<GeneralSubtree> permittedSubtrees = jgsPermittedSubtrees.getGeneralSubtrees().getGeneralSubtrees();
    List<GeneralSubtree> excludedSubtrees = jgsExcludedSubtrees.getGeneralSubtrees().getGeneralSubtrees();

    GeneralSubtree[] permittedSubtreesArray = permittedSubtrees
            .toArray(new GeneralSubtree[permittedSubtrees.size()]);
    GeneralSubtree[] excludedSubtreesArray = excludedSubtrees
            .toArray(new GeneralSubtree[excludedSubtrees.size()]);

    NameConstraints nameConstraints = new NameConstraints(permittedSubtreesArray, excludedSubtreesArray);

    try {//from   ww  w.  java 2s . c om
        value = nameConstraints.getEncoded(ASN1Encoding.DER);
    } catch (IOException ex) {
        DError dError = new DError(this, ex);
        dError.setLocationRelativeTo(this);
        dError.setVisible(true);
        return;
    }

    closeDialog();
}

From source file:org.cesecore.certificates.certificate.certextensions.standard.NameConstraint.java

License:Open Source License

@Override
public ASN1Encodable getValue(EndEntityInformation userData, CA ca, CertificateProfile certProfile,
        PublicKey userPublicKey, PublicKey caPublicKey, CertificateValidity val)
        throws CertificateExtensionException {
    NameConstraints nc = null;// w ww  .  ja  v  a2 s . c  om

    if (!(ca instanceof X509CA)) {
        throw new CertificateExtensionException("Can't issue non-X509 certificate with Name Constraint");
    }

    final ExtendedInformation ei = userData.getExtendedinformation();
    if (ei != null) {
        final List<String> permittedNames = ei.getNameConstraintsPermitted();
        final List<String> excludedNames = ei.getNameConstraintsExcluded();

        if (permittedNames != null || excludedNames != null) {
            final GeneralSubtree[] permitted = toGeneralSubtrees(permittedNames);
            final GeneralSubtree[] excluded = toGeneralSubtrees(excludedNames);

            // Do not include an empty name constraints extension
            if (permitted.length != 0 || excluded.length != 0) {
                nc = new NameConstraints(permitted, excluded);
            }
        }
    }

    return nc;
}

From source file:org.cesecore.util.CertToolsTest.java

License:Open Source License

/**
 * Tests the following methods:/*from  w  ww .  j  av a 2s  .c o m*/
 * <ul>
 * <li>{@link CertTools.checkNameConstraints}</li>
 * <li>{@link NameConstraint.parseNameConstraintsList}</li>
 * <li>{@link NameConstraint.toGeneralSubtrees}</li>
 * </ul>
 */
@Test
public void testNameConstraints() throws Exception {
    final String permitted = "C=SE,CN=example.com\n" + "example.com\n" + "@mail.example\n" + "user@host.com\n"
            + "10.0.0.0/8\n" + "   C=SE,  CN=spacing    \n";
    final String excluded = "forbidden.example.com\n" + "postmaster@mail.example\n" + "10.1.0.0/16\n" + "::/0"; // IPv6

    final List<Extension> extensions = new ArrayList<Extension>();
    GeneralSubtree[] permittedSubtrees = NameConstraint
            .toGeneralSubtrees(NameConstraint.parseNameConstraintsList(permitted));
    GeneralSubtree[] excludedSubtrees = NameConstraint
            .toGeneralSubtrees(NameConstraint.parseNameConstraintsList(excluded));
    byte[] extdata = new NameConstraints(permittedSubtrees, excludedSubtrees).toASN1Primitive().getEncoded();
    extensions.add(new Extension(Extension.nameConstraints, false, extdata));

    final KeyPair testkeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    X509Certificate cacert = CertTools.genSelfCertForPurpose("C=SE,CN=Test Name Constraints CA", 365, null,
            testkeys.getPrivate(), testkeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true,
            X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign, null, null, "BC", true, extensions);

    // Allowed subject DNs
    final X500Name validDN = new X500Name("C=SE,CN=example.com"); // re-used below
    CertTools.checkNameConstraints(cacert, validDN, null);
    CertTools.checkNameConstraints(cacert, new X500Name("C=SE,CN=spacing"), null);

    // Allowed subject alternative names
    CertTools.checkNameConstraints(cacert, validDN,
            new GeneralNames(new GeneralName(GeneralName.dNSName, "example.com")));
    CertTools.checkNameConstraints(cacert, validDN,
            new GeneralNames(new GeneralName(GeneralName.dNSName, "x.sub.example.com")));
    CertTools.checkNameConstraints(cacert, validDN,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "someuser@mail.example")));
    CertTools.checkNameConstraints(cacert, validDN,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "user@host.com")));
    CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.iPAddress,
            new DEROctetString(InetAddress.getByName("10.0.0.1").getAddress()))));
    CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.iPAddress,
            new DEROctetString(InetAddress.getByName("10.255.255.255").getAddress()))));

    // Disallowed subject DN
    checkNCException(cacert, new X500Name("C=DK,CN=example.com"), null,
            "Disallowed DN (wrong field value) was accepted");
    checkNCException(cacert, new X500Name("C=SE,O=Company,CN=example.com"), null,
            "Disallowed DN (extra field) was accepted");

    // Disallowed SAN
    // The commented out lines are allowed by BouncyCastle but disallowed by the RFC
    checkNCException(cacert, validDN, new GeneralName(GeneralName.dNSName, "bad.com"),
            "Disallowed SAN (wrong DNS name) was accepted");
    checkNCException(cacert, validDN, new GeneralName(GeneralName.dNSName, "forbidden.example.com"),
            "Disallowed SAN (excluded DNS subdomain) was accepted");
    checkNCException(cacert, validDN, new GeneralName(GeneralName.rfc822Name, "wronguser@host.com"),
            "Disallowed SAN (wrong e-mail) was accepted");
    checkNCException(cacert, validDN,
            new GeneralName(GeneralName.iPAddress,
                    new DEROctetString(InetAddress.getByName("10.1.0.1").getAddress())),
            "Disallowed SAN (excluded IPv4 address) was accepted");
    checkNCException(cacert, validDN,
            new GeneralName(GeneralName.iPAddress,
                    new DEROctetString(InetAddress.getByName("192.0.2.1").getAddress())),
            "Disallowed SAN (wrong IPv4 address) was accepted");
    checkNCException(cacert, validDN,
            new GeneralName(GeneralName.iPAddress,
                    new DEROctetString(InetAddress.getByName("2001:DB8::").getAddress())),
            "Disallowed SAN (IPv6 address) was accepted");
}

From source file:org.conscrypt.java.security.TestKeyStore.java

License:Apache License

private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey,
        X500Principal subject, X500Principal issuer, int keyUsage, boolean ca,
        List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages,
        List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints,
        List<GeneralSubtree> excludedNameConstraints, BigInteger serialNumber) throws Exception {
    // Note that there is no way to programmatically make a
    // Certificate using java.* or javax.* APIs. The
    // CertificateFactory interface assumes you want to read
    // in a stream of bytes, typically the X.509 factory would
    // allow ASN.1 DER encoded bytes and optionally some PEM
    // formats. Here we use Bouncy Castle's
    // X509V3CertificateGenerator and related classes.

    long millisPerDay = 24 * 60 * 60 * 1000;
    long now = System.currentTimeMillis();
    Date start = new Date(now - millisPerDay);
    Date end = new Date(now + millisPerDay);

    String keyAlgorithm = privateKey.getAlgorithm();
    String signatureAlgorithm;// w  w w . j av  a 2  s  .  c o m
    if (keyAlgorithm.equals("RSA")) {
        signatureAlgorithm = "sha256WithRSA";
    } else if (keyAlgorithm.equals("DSA")) {
        signatureAlgorithm = "sha256WithDSA";
    } else if (keyAlgorithm.equals("EC")) {
        signatureAlgorithm = "sha256WithECDSA";
    } else if (keyAlgorithm.equals("EC_RSA")) {
        signatureAlgorithm = "sha256WithRSA";
    } else {
        throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
    }

    if (serialNumber == null) {
        byte[] serialBytes = new byte[16];
        new SecureRandom().nextBytes(serialBytes);
        serialNumber = new BigInteger(1, serialBytes);
    }

    X509v3CertificateBuilder x509cg = new X509v3CertificateBuilder(X500Name.getInstance(issuer.getEncoded()),
            serialNumber, start, end, X500Name.getInstance(subject.getEncoded()),
            SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()));
    if (keyUsage != 0) {
        x509cg.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage));
    }
    if (ca) {
        x509cg.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    }
    for (int i = 0; i < extendedKeyUsages.size(); i++) {
        KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
        boolean critical = criticalExtendedKeyUsages.get(i);
        x509cg.addExtension(Extension.extendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
    }
    if (!subjectAltNames.isEmpty()) {
        x509cg.addExtension(Extension.subjectAlternativeName, false,
                new GeneralNames(subjectAltNames.toArray(new GeneralName[0])).getEncoded());
    }
    if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
        x509cg.addExtension(Extension.nameConstraints, true,
                new NameConstraints(
                        permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]),
                        excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
    }

    X509CertificateHolder x509holder = x509cg
            .build(new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey));
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    X509Certificate x509c = (X509Certificate) certFactory
            .generateCertificate(new ByteArrayInputStream(x509holder.getEncoded()));
    if (StandardNames.IS_RI) {
        /*
         * The RI can't handle the BC EC signature algorithm
         * string of "ECDSA", since it expects "...WITHEC...",
         * so convert from BC to RI X509Certificate
         * implementation via bytes.
         */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
        Certificate c = cf.generateCertificate(bais);
        x509c = (X509Certificate) c;
    }
    return x509c;
}

From source file:org.tdmx.client.crypto.certificate.CredentialUtils.java

License:Open Source License

/**
 * Create the credentials of a ZoneAdministrator.
 * /* ww  w . j a  v a2  s.c  om*/
 * The ZoneAdministrator credentials are long validity.
 * 
 * @param req
 * @return
 * @throws CryptoCertificateException
 */
public static PKIXCredential createZoneAdministratorCredential(ZoneAdministrationCredentialSpecifier req)
        throws CryptoCertificateException {
    KeyPair kp = null;
    try {
        kp = req.getKeyAlgorithm().generateNewKeyPair();
    } catch (CryptoException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_KEYPAIR_GENERATION, e);
    }

    PublicKey publicKey = kp.getPublic();
    PrivateKey privateKey = kp.getPrivate();

    X500NameBuilder subjectBuilder = new X500NameBuilder();
    if (StringUtils.hasText(req.getCountry())) {
        subjectBuilder.addRDN(BCStyle.C, req.getCountry());
    }
    if (StringUtils.hasText(req.getLocation())) {
        subjectBuilder.addRDN(BCStyle.L, req.getLocation());
    }
    if (StringUtils.hasText(req.getOrg())) {
        subjectBuilder.addRDN(BCStyle.O, req.getOrg());
    }
    if (StringUtils.hasText(req.getOrgUnit())) {
        if (TDMX_DOMAIN_CA_OU.equals(req.getOrgUnit())) {
            throw new CryptoCertificateException(CertificateResultCode.ERROR_INVALID_OU);
        }
        subjectBuilder.addRDN(BCStyle.OU, req.getOrgUnit());
    }
    if (StringUtils.hasText(req.getEmailAddress())) {
        subjectBuilder.addRDN(BCStyle.E, req.getEmailAddress());
    }
    if (StringUtils.hasText(req.getTelephoneNumber())) {
        subjectBuilder.addRDN(BCStyle.TELEPHONE_NUMBER, req.getTelephoneNumber());
    }
    if (StringUtils.hasText(req.getCn())) {
        subjectBuilder.addRDN(BCStyle.CN, req.getCn());
    }
    X500Name subject = subjectBuilder.build();
    X500Name issuer = subject;
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, new BigInteger("1"),
            req.getNotBefore().getTime(), req.getNotAfter().getTime(), subject, publicKey);

    try {
        BasicConstraints cA = new BasicConstraints(1);
        certBuilder.addExtension(Extension.basicConstraints, true, cA);

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(publicKey));
        certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                extUtils.createSubjectKeyIdentifier(publicKey));

        KeyUsage ku = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign);
        certBuilder.addExtension(Extension.keyUsage, false, ku);

        // RFC5280 http://tools.ietf.org/html/rfc5280#section-4.2.1.10
        // The CA has a CN which is not part of the name constraint - but we can constrain
        // any domain certificate issued to be limited to some OU under the O.
        X500NameBuilder subjectConstraintBuilder = new X500NameBuilder();
        if (StringUtils.hasText(req.getCountry())) {
            subjectConstraintBuilder.addRDN(BCStyle.C, req.getCountry());
        }
        if (StringUtils.hasText(req.getLocation())) {
            subjectConstraintBuilder.addRDN(BCStyle.L, req.getLocation());
        }
        if (StringUtils.hasText(req.getOrg())) {
            subjectConstraintBuilder.addRDN(BCStyle.O, req.getOrg());
        }
        if (StringUtils.hasText(req.getOrgUnit())) {
            subjectConstraintBuilder.addRDN(BCStyle.OU, req.getOrgUnit());
        }
        subjectConstraintBuilder.addRDN(BCStyle.OU, TDMX_DOMAIN_CA_OU);
        X500Name nameConstraint = subjectConstraintBuilder.build();

        GeneralName snc = new GeneralName(GeneralName.directoryName, nameConstraint);
        GeneralSubtree snSubtree = new GeneralSubtree(snc, new BigInteger("0"), null);
        NameConstraints nc = new NameConstraints(new GeneralSubtree[] { snSubtree }, null);
        certBuilder.addExtension(Extension.nameConstraints, true, nc);

        certBuilder.addExtension(TdmxZoneInfo.tdmxZoneInfo, false, req.getZoneInfo());

        ContentSigner signer = SignatureAlgorithm.getContentSigner(privateKey, req.getSignatureAlgorithm());
        byte[] certBytes = certBuilder.build(signer).getEncoded();

        PKIXCertificate c = CertificateIOUtils.decodeX509(certBytes);

        return new PKIXCredential(c, privateKey);
    } catch (CertIOException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_CERT_GENERATION, e);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_CERT_GENERATION, e);
    } catch (IOException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_CERT_GENERATION, e);
    }
}

From source file:org.tdmx.client.crypto.certificate.CredentialUtils.java

License:Open Source License

/**
 * Create the credentials of a DomainAdministrator.
 * //from  ww w.  j a  v  a2s . co m
 * @param req
 * @return
 * @throws CryptoCertificateException
 */
public static PKIXCredential createDomainAdministratorCredential(DomainAdministrationCredentialSpecifier req)
        throws CryptoCertificateException {
    KeyPair kp = null;
    try {
        kp = req.getKeyAlgorithm().generateNewKeyPair();
    } catch (CryptoException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_KEYPAIR_GENERATION, e);
    }

    PublicKey publicKey = kp.getPublic();
    PrivateKey privateKey = kp.getPrivate();

    PKIXCredential issuerCredential = req.getZoneAdministratorCredential();
    PKIXCertificate issuerPublicCert = issuerCredential.getPublicCert();

    PublicKey issuerPublicKey = issuerPublicCert.getCertificate().getPublicKey();
    PrivateKey issuerPrivateKey = issuerCredential.getPrivateKey();

    X500NameBuilder subjectBuilder = new X500NameBuilder();
    if (StringUtils.hasText(issuerPublicCert.getCountry())) {
        subjectBuilder.addRDN(BCStyle.C, issuerPublicCert.getCountry());
    }
    if (StringUtils.hasText(issuerPublicCert.getLocation())) {
        subjectBuilder.addRDN(BCStyle.L, issuerPublicCert.getLocation());
    }
    if (StringUtils.hasText(issuerPublicCert.getOrganization())) {
        subjectBuilder.addRDN(BCStyle.O, issuerPublicCert.getOrganization());
    }
    if (StringUtils.hasText(issuerPublicCert.getOrgUnit())) {
        subjectBuilder.addRDN(BCStyle.OU, issuerPublicCert.getOrgUnit());
    }
    subjectBuilder.addRDN(BCStyle.OU, TDMX_DOMAIN_CA_OU);
    subjectBuilder.addRDN(BCStyle.CN, req.getDomainName());
    X500Name subject = subjectBuilder.build();
    X500Name issuer = issuerPublicCert.getSubjectName();
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, new BigInteger("1"),
            req.getNotBefore().getTime(), req.getNotAfter().getTime(), subject, publicKey);

    try {
        BasicConstraints cA = new BasicConstraints(0);
        certBuilder.addExtension(Extension.basicConstraints, true, cA);

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(issuerPublicKey));
        certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                extUtils.createSubjectKeyIdentifier(publicKey));

        KeyUsage ku = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign);
        certBuilder.addExtension(Extension.keyUsage, false, ku);

        // RFC5280 http://tools.ietf.org/html/rfc5280#section-4.2.1.10
        // The CA has a CN which is not part of the name constraint - but we can constrain
        // any domain certificate issued to be limited to some OU under the O.
        X500NameBuilder subjectConstraintBuilder = new X500NameBuilder();
        if (StringUtils.hasText(issuerPublicCert.getCountry())) {
            subjectConstraintBuilder.addRDN(BCStyle.C, issuerPublicCert.getCountry());
        }
        if (StringUtils.hasText(issuerPublicCert.getLocation())) {
            subjectConstraintBuilder.addRDN(BCStyle.L, issuerPublicCert.getLocation());
        }
        if (StringUtils.hasText(issuerPublicCert.getOrganization())) {
            subjectConstraintBuilder.addRDN(BCStyle.O, issuerPublicCert.getOrganization());
        }
        if (StringUtils.hasText(issuerPublicCert.getOrgUnit())) {
            subjectConstraintBuilder.addRDN(BCStyle.OU, issuerPublicCert.getOrgUnit());
        }
        subjectConstraintBuilder.addRDN(BCStyle.OU, TDMX_DOMAIN_CA_OU);
        subjectConstraintBuilder.addRDN(BCStyle.OU, req.getDomainName());
        X500Name nameConstraint = subjectConstraintBuilder.build();

        GeneralName snc = new GeneralName(GeneralName.directoryName, nameConstraint);
        GeneralSubtree snSubtree = new GeneralSubtree(snc, new BigInteger("0"), null);
        NameConstraints nc = new NameConstraints(new GeneralSubtree[] { snSubtree }, null);
        certBuilder.addExtension(Extension.nameConstraints, true, nc);

        certBuilder.addExtension(TdmxZoneInfo.tdmxZoneInfo, false, issuerPublicCert.getTdmxZoneInfo());

        ContentSigner signer = SignatureAlgorithm.getContentSigner(issuerPrivateKey,
                req.getSignatureAlgorithm());
        byte[] certBytes = certBuilder.build(signer).getEncoded();

        PKIXCertificate c = CertificateIOUtils.decodeX509(certBytes);

        return new PKIXCredential(c, issuerCredential.getCertificateChain(), privateKey);
    } catch (CertIOException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_CERT_GENERATION, e);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_CERT_GENERATION, e);
    } catch (IOException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_CERT_GENERATION, e);
    }
}

From source file:org.xipki.ca.certprofile.XmlX509CertprofileUtil.java

License:Open Source License

public static NameConstraints buildNameConstrains(final org.xipki.ca.certprofile.x509.jaxb.NameConstraints type)
        throws CertprofileException {
    GeneralSubtree[] permitted = buildGeneralSubtrees(type.getPermittedSubtrees());
    GeneralSubtree[] excluded = buildGeneralSubtrees(type.getExcludedSubtrees());
    if (permitted == null && excluded == null) {
        return null;
    }//from  w  w  w. jav a2 s. c o  m
    return new NameConstraints(permitted, excluded);
}