Example usage for org.bouncycastle.asn1.x509 GeneralName dNSName

List of usage examples for org.bouncycastle.asn1.x509 GeneralName dNSName

Introduction

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

Prototype

int dNSName

To view the source code for org.bouncycastle.asn1.x509 GeneralName dNSName.

Click Source Link

Usage

From source file:be.fedict.eid.pkira.crypto.certificate.CertificateInfo.java

License:Open Source License

public List<String> getAlternativeNames() throws CryptoException {
    try {/*from  ww  w .ja  v  a2 s .c  o m*/
        List<String> result = new ArrayList<String>();

        byte[] extensionBytes = certificate.getExtensionValue(X509Extension.subjectAlternativeName.getId());
        ASN1OctetString octs = (ASN1OctetString) ASN1Object.fromByteArray(extensionBytes);
        DERSequence extension = (DERSequence) ASN1Object.fromByteArray(octs.getOctets());

        for (int i = 0; i < extension.size(); i++) {
            GeneralName name = GeneralName.getInstance(extension.getObjectAt(i));
            if (name.getTagNo() == GeneralName.dNSName) {
                result.add(name.getName().toString());
            }
        }

        return result;
    } catch (IOException e) {
        throw new CryptoException("Could not extract SAN value.", e);
    }
}

From source file:be.fedict.eid.pkira.crypto.csr.CSRInfo.java

License:Open Source License

public List<String> getSubjectAlternativeNames() throws CryptoException {
    List<String> result = new ArrayList<String>();

    ASN1Set attributes = certificationRequest.getCertificationRequestInfo().getAttributes();
    for (DERSet extension : getElementsFromASN1Set(attributes, CSR_EXTENSION_ATTRIBUTE_ID, DERSet.class)) {
        for (DEROctetString extensionValue : getElementsFromASN1Set(extension,
                X509Extension.subjectAlternativeName, DEROctetString.class)) {
            try {
                ASN1Object bytes = ASN1Object.fromByteArray(extensionValue.getOctets());
                GeneralNames names = GeneralNames.getInstance(bytes);
                for (GeneralName name : names.getNames()) {
                    if (name.getTagNo() == GeneralName.dNSName) {
                        String theName = name.getName().toString();
                        if (theName.indexOf('*') != -1) {
                            throw new CryptoException(
                                    "Subject Alternative Names are not allowed to contain wildcards.");
                        }/*  w  w  w .  j  a  v  a 2  s .c om*/
                        result.add(theName);
                    } else {
                        throw new CryptoException(
                                "Only Subject Alternative Name of type DNS is allowed in the CSR.");
                    }
                }
            } catch (IOException e) {
                throw new CryptoException("Could not extract SAN value.", e);
            }
        }
    }

    return result;
}

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 .ja v a2s  . c om*/
    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.foilen.smalltools.crypt.bouncycastle.cert.RSACertificate.java

License:Open Source License

/**
 * Sign the {@link #setKeysForSigning(AsymmetricKeys)} with itself and put it in certificateHolder.
 *
 * @param certificateDetails/* ww w .  j a v  a 2  s.c o m*/
 *            some information to store in the certificate
 * @return this
 */
public RSACertificate selfSign(CertificateDetails certificateDetails) {

    AssertTools.assertNotNull(keysForSigning, "The keysForSigning is not set");
    AssertTools.assertNull(certificateHolder, "The certificate already exists");

    try {
        RSAKeyDetails keyDetails = rsaCrypt.retrieveKeyDetails(keysForSigning);
        PrivateKey privKey = keyDetails.getJcaPrivateKey();
        PublicKey publicKey = keyDetails.getJcaPublicKey();
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(privKey);
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

        Date startDate = certificateDetails.getStartDate();
        Date endDate = certificateDetails.getEndDate();
        BigInteger serial = certificateDetails.getSerial();

        // Common Name
        X500Name issuer = new X500Name("CN=" + certificateDetails.getCommonName());

        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(issuer, serial, startDate,
                endDate, issuer, subPubKeyInfo);

        // Subject Alternative Names (DNS)
        if (!CollectionsTools.isNullOrEmpty(certificateDetails.getSanDns())) {
            GeneralName[] altNames = new GeneralName[certificateDetails.getSanDns().size()];
            int i = 0;
            for (String sanDns : certificateDetails.getSanDns()) {
                altNames[i++] = new GeneralName(GeneralName.dNSName, sanDns);
            }
            GeneralNames subjectAltNames = new GeneralNames(altNames);
            certificateBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
        }
        certificateHolder = certificateBuilder.build(sigGen);

        return this;
    } catch (Exception e) {
        throw new SmallToolsException("Problem signing the key", e);
    }
}

From source file:com.foilen.smalltools.crypt.bouncycastle.cert.RSACertificate.java

License:Open Source License

/**
 * Sign another public key./*w  w  w  . jav a 2s.c  o  m*/
 *
 * @param publicKeyToSign
 *            the public key to sign
 * @param certificateDetails
 *            some information to store in the certificate
 * @return the new certificate
 */
public RSACertificate signPublicKey(AsymmetricKeys publicKeyToSign, CertificateDetails certificateDetails) {

    try {
        PrivateKey privKey = rsaCrypt.retrieveKeyDetails(keysForSigning).getJcaPrivateKey();
        PublicKey publicKey = rsaCrypt.retrieveKeyDetails(publicKeyToSign).getJcaPublicKey();
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(privKey);
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

        Date startDate = certificateDetails.getStartDate();
        Date endDate = certificateDetails.getEndDate();
        BigInteger serial = certificateDetails.getSerial();

        X500Name issuer = new X500Name("CN=" + getCommonName());
        X500Name subject = new X500Name("CN=" + certificateDetails.getCommonName());

        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(issuer, serial, startDate,
                endDate, subject, subPubKeyInfo);

        // Subject Alternative Names (DNS)
        if (!CollectionsTools.isNullOrEmpty(certificateDetails.getSanDns())) {
            GeneralName[] altNames = new GeneralName[certificateDetails.getSanDns().size()];
            int i = 0;
            for (String sanDns : certificateDetails.getSanDns()) {
                altNames[i++] = new GeneralName(GeneralName.dNSName, sanDns);
            }
            GeneralNames subjectAltNames = new GeneralNames(altNames);
            certificateBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
        }

        X509CertificateHolder newCert = certificateBuilder.build(sigGen);

        return new RSACertificate(newCert, publicKeyToSign);
    } catch (Exception e) {
        throw new SmallToolsException("Problem signing the key", e);
    }
}

From source file:com.github.spyhunter99.simplejks.CertGenBouncy.java

public static java.security.cert.Certificate selfSign(KeyPair keyPair, String subjectDN)
        throws OperatorCreationException, CertificateException, IOException {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);

    long now = System.currentTimeMillis();
    Date startDate = new Date(now);

    X500Name dnName = new X500Name(subjectDN);
    BigInteger certSerialNumber = new BigInteger(Long.toString(now)); // <-- Using the current timestamp as the certificate serial number

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);/*ww  w  .ja  v a2s  . c o  m*/
    calendar.add(Calendar.YEAR, 30); // <-- 1 Yr validity

    Date endDate = calendar.getTime();

    String signatureAlgorithm = "SHA256WithRSA"; // <-- Use appropriate signature algorithm based on your keyPair algorithm.

    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());

    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber,
            startDate, endDate, dnName, keyPair.getPublic());

    // Extensions --------------------------
    // Basic Constraints
    BasicConstraints basicConstraints = new BasicConstraints(true); // <-- true for CA, false for EndEntity

    certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); // Basic Constraints is usually marked as critical.

    ASN1Encodable[] subjectAlternativeNames = new ASN1Encodable[] {
            new GeneralName(GeneralName.dNSName, "server"),
            new GeneralName(GeneralName.dNSName, "server.mydomain.com") };
    DERSequence subjectAlternativeNamesExtension = new DERSequence(subjectAlternativeNames);
    certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAlternativeNamesExtension);

    // -------------------------------------
    return new JcaX509CertificateConverter().setProvider(bcProvider)
            .getCertificate(certBuilder.build(contentSigner));
}

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

License:Apache License

/**
 * @see com.otterca.repository.util.X509CertificateBuilder#setDnsNames(java.lang
 *      .String)//w  ww .  jav  a  2 s  . c  o  m
 */
@Override
public X509CertificateBuilder setDnsNames(String... dnsNames) {
    for (String name : dnsNames) {
        subjectNames.add(new GeneralName(GeneralName.dNSName, name));
    }
    return this;
}

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

License:Apache License

/**
 * @see com.otterca.repository.util.X509CertificateBuilder#setIssuerDnsNames(java.lang.String)
 *///from  w  ww.  j a  v  a 2 s.c o  m
@Override
public X509CertificateBuilder setIssuerDnsNames(String... dnsNames) {
    for (String name : dnsNames) {
        issuerNames.add(new GeneralName(GeneralName.dNSName, name));
    }
    return this;
}

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

License:Apache License

/**
 * @see com.otterca.common.crypto.X509CertificateBuilder#setTimestampingLocations(com.otterca.common.crypto.GeneralName...)
 *//*from   w  w  w  .j  a va2s  .  co  m*/
@Override
public X509CertificateBuilder setTimestampingLocations(com.otterca.common.crypto.GeneralName<?>... names) {
    timestamping.clear();
    for (com.otterca.common.crypto.GeneralName<?> name : names) {
        switch (name.getType()) {
        case URI:
            timestamping.add(new GeneralName(GeneralName.uniformResourceIdentifier, name.get().toString()));
            break;
        case EMAIL:
            timestamping.add(new GeneralName(GeneralName.rfc822Name, name.get().toString()));
            break;
        case DNS:
            timestamping.add(new GeneralName(GeneralName.dNSName, name.get().toString()));
            break;
        case IP_ADDRESS:
            timestamping
                    .add(new GeneralName(GeneralName.iPAddress, ((InetAddress) name.get()).getHostAddress()));
            break;
        default:
            throw new IllegalArgumentException("unexpected type for Timestamping location: " + name.getType());
        }
    }
    return this;
}

From source file:com.yacme.ext.oxsit.cust_it.security.crl.X509CertRL.java

License:Open Source License

private static String decodeAGeneralName(GeneralName genName) throws IOException {
    switch (genName.getTagNo()) {
    //only URI are used here, the other protocols are ignored
    case GeneralName.uniformResourceIdentifier:
        return ((DERString) genName.getName()).getString();
    case GeneralName.ediPartyName:
    case GeneralName.x400Address:
    case GeneralName.otherName:
    case GeneralName.directoryName:
    case GeneralName.dNSName:
    case GeneralName.rfc822Name:
    case GeneralName.registeredID:
    case GeneralName.iPAddress:
        break;//from   www.ja v  a  2  s. c  o m
    default:
        throw new IOException("Bad tag number: " + genName.getTagNo());
    }
    return null;
}