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

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

Introduction

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

Prototype

int iPAddress

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

Click Source Link

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;/* w  w  w.j av  a  2 s .c o 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.gitblit.utils.X509Utils.java

License:Apache License

/**
 * Creates a new SSL certificate signed by the CA private key and stored in
 * keyStore.// w  w w .j av a  2 s. c  om
 *
 * @param sslMetadata
 * @param caPrivateKey
 * @param caCert
 * @param targetStoreFile
 * @param x509log
 */
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey,
        X509Certificate caCert, File targetStoreFile, X509Log x509log) {
    try {
        KeyPair pair = newKeyPair();

        X500Name webDN = buildDistinguishedName(sslMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN,
                BigInteger.valueOf(System.currentTimeMillis()), sslMetadata.notBefore, sslMetadata.notAfter,
                webDN, pair.getPublic());

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
                extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));

        // support alternateSubjectNames for SSL certificates
        List<GeneralName> altNames = new ArrayList<GeneralName>();
        if (HttpUtils.isIpAddress(sslMetadata.commonName)) {
            altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
        }
        if (altNames.size() > 0) {
            GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }

        ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC)
                .build(caPrivateKey);
        X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
                .getCertificate(certBuilder.build(caSigner));

        cert.checkValidity(new Date());
        cert.verify(caCert.getPublicKey());

        // Save to keystore
        KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password);
        serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(),
                new Certificate[] { cert, caCert });
        saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);

        x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(),
                cert.getSubjectDN().getName()));

        // update serial number in metadata object
        sslMetadata.serialNumber = cert.getSerialNumber().toString();

        return cert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate SSL certificate!", t);
    }
}

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

License:Apache License

/**
 * @see com.otterca.repository.util.X509CertificateBuilder#setIpAddresses(java
 *      .lang.String)/*from  w w  w  .  j a va2s. co m*/
 */
@Override
public X509CertificateBuilder setIpAddresses(String... ipAddresses) {
    for (String address : ipAddresses) {
        subjectNames.add(new GeneralName(GeneralName.iPAddress, address));
    }
    return this;
}

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

License:Apache License

/**
 * @see com.otterca.repository.util.X509CertificateBuilder#setIssuerIpAddresses
 *      (java.lang.String)//from www.  j a v  a2 s . c  om
 */
@Override
public X509CertificateBuilder setIssuerIpAddresses(String... ipAddresses) {
    for (String address : ipAddresses) {
        issuerNames.add(new GeneralName(GeneralName.iPAddress, address));
    }
    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  av  a 2s. c om*/
@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 w w  w. ja  v  a 2 s .c o m*/
    default:
        throw new IOException("Bad tag number: " + genName.getTagNo());
    }
    return null;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) {

    List<String> ipAddresses = new ArrayList<>();
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == GeneralName.iPAddress) {
                    try {
                        InetAddress addr = InetAddress
                                .getByAddress(((DEROctetString) name.getName()).getOctets());
                        ipAddresses.add(addr.getHostAddress());
                    } catch (UnknownHostException e) {
                    }/*www. j  ava2 s  . c  om*/
                }
            }
        }
    }
    return ipAddresses;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static List<String> extractX509CertIPAddresses(X509Certificate x509Cert) {

    Collection<List<?>> altNames = null;
    try {//w w w.  j  av a2 s  . c om
        altNames = x509Cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException ex) {
        LOG.error("extractX509IPAddresses: Caught CertificateParsingException when parsing certificate: "
                + ex.getMessage());
    }

    if (altNames == null) {
        return Collections.emptyList();
    }

    List<String> ipAddresses = new ArrayList<>();
    for (@SuppressWarnings("rawtypes")
    List item : altNames) {
        Integer type = (Integer) item.get(0);

        // GeneralName ::= CHOICE {
        //     otherName                       [0]     OtherName,
        //     rfc822Name                      [1]     IA5String,
        //     dNSName                         [2]     IA5String,
        //     x400Address                     [3]     ORAddress,
        //     directoryName                   [4]     Name,
        //     ediPartyName                    [5]     EDIPartyName,
        //     uniformResourceIdentifier       [6]     IA5String,
        //     iPAddress                       [7]     OCTET STRING,
        //     registeredID                    [8]     OBJECT IDENTIFIER}

        if (type == GeneralName.iPAddress) {
            ipAddresses.add((String) item.get(1));
        }
    }
    return ipAddresses;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq,
        PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {

    // set validity for the given number of minutes from now

    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);//from w w  w . ja  v a2 s  .  c o m
    cal.add(Calendar.MINUTE, validityTimeout);
    Date notAfter = cal.getTime();

    // Generate self-signed certificate

    X509Certificate cert = null;
    try {
        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(
                certReq);
        PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();

        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer,
                BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(),
                publicKey)
                        .addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints))
                        .addExtension(Extension.keyUsage, true,
                                new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment))
                        .addExtension(Extension.extendedKeyUsage, true,
                                new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth,
                                        KeyPurposeId.id_kp_serverAuth }));

        // see if we have the dns/rfc822/ip address extensions specified in the csr

        ArrayList<GeneralName> altNames = new ArrayList<>();
        Attribute[] certAttributes = jcaPKCS10CertificationRequest
                .getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (certAttributes != null && certAttributes.length > 0) {
            for (Attribute attribute : certAttributes) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns == null) {
                    continue;
                }
                GeneralName[] names = gns.getNames();
                for (int i = 0; i < names.length; i++) {
                    switch (names[i].getTagNo()) {
                    case GeneralName.dNSName:
                    case GeneralName.iPAddress:
                    case GeneralName.rfc822Name:
                        altNames.add(names[i]);
                        break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false,
                        new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])));
            }
        }

        String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
        ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER)
                .build(caPrivateKey);

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
        cert = converter.getCertificate(caBuilder.build(caSigner));

    } catch (CertificateException ex) {
        LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error(
                "generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (InvalidKeyException ex) {
        LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(
                "generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("generateX509Certificate: unable to generate X509 Certificate: " + ex.getMessage());
        throw new CryptoException("Unable to generate X509 Certificate");
    }

    return cert;
}

From source file:de.mendelson.util.security.cert.KeystoreCertificate.java

/**
 * Converts the tag no of a general name to a human readable value
 *//*from ww  w  .  j a v  a  2 s  .  c om*/
private String generalNameTagNoToString(GeneralName name) {
    if (name.getTagNo() == GeneralName.dNSName) {
        return ("DNS name");
    }
    if (name.getTagNo() == GeneralName.directoryName) {
        return ("Directory name");
    }
    if (name.getTagNo() == GeneralName.ediPartyName) {
        return ("EDI party name");
    }
    if (name.getTagNo() == GeneralName.iPAddress) {
        return ("IP address");
    }
    if (name.getTagNo() == GeneralName.otherName) {
        return ("Other name");
    }
    if (name.getTagNo() == GeneralName.registeredID) {
        return ("Registered ID");
    }
    if (name.getTagNo() == GeneralName.rfc822Name) {
        return ("RFC822 name");
    }
    if (name.getTagNo() == GeneralName.uniformResourceIdentifier) {
        return ("URI");
    }
    if (name.getTagNo() == GeneralName.x400Address) {
        return ("x.400 address");
    }
    return ("");
}