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:org.apache.zookeeper.common.X509TestHelpers.java

License:Apache License

/**
 * Returns subject alternative names for "localhost".
 * @return the subject alternative names for "localhost".
 *//*  w  ww  .  jav  a2 s  .c  om*/
private static GeneralNames getLocalhostSubjectAltNames() throws UnknownHostException {
    InetAddress[] localAddresses = InetAddress.getAllByName("localhost");
    GeneralName[] generalNames = new GeneralName[localAddresses.length + 1];
    for (int i = 0; i < localAddresses.length; i++) {
        generalNames[i] = new GeneralName(GeneralName.iPAddress,
                new DEROctetString(localAddresses[i].getAddress()));
    }
    generalNames[generalNames.length - 1] = new GeneralName(GeneralName.dNSName, new DERIA5String("localhost"));
    return new GeneralNames(generalNames);
}

From source file:org.apache.zookeeper.common.ZKTrustManagerTest.java

License:Apache License

private X509Certificate[] createSelfSignedCertifcateChain(String ipAddress, String hostname) throws Exception {
    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, "NOT_LOCALHOST");
    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);//from w  w  w. j  a  va  2 s.  com
    cal.add(Calendar.YEAR, 1);
    Date notAfter = cal.getTime();
    BigInteger serialNumber = new BigInteger(128, new Random());

    X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(),
            serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic())
                    .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
                    .addExtension(Extension.keyUsage, true,
                            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    List<GeneralName> generalNames = new ArrayList<>();
    if (ipAddress != null) {
        generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress));
    }
    if (hostname != null) {
        generalNames.add(new GeneralName(GeneralName.dNSName, hostname));
    }

    if (!generalNames.isEmpty()) {
        certificateBuilder.addExtension(Extension.subjectAlternativeName, true,
                new GeneralNames(generalNames.toArray(new GeneralName[] {})));
    }

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

    return new X509Certificate[] {
            new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner)) };
}

From source file:org.apache.zookeeper.server.quorum.QuorumSSLTest.java

License:Apache License

public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey,
        String hostname, String ipAddress, String crlPath, Integer ocspPort) throws Exception {
    X509CertificateHolder holder = new JcaX509CertificateHolder(caCert);
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey);

    List<GeneralName> generalNames = new ArrayList<>();
    if (hostname != null) {
        generalNames.add(new GeneralName(GeneralName.dNSName, hostname));
    }/*  w w w  . j  a  v  a  2 s .c om*/

    if (ipAddress != null) {
        generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress));
    }

    SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory
            .createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()));
    X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils();
    X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(holder.getSubject(),
            new BigInteger(128, new Random()), certStartTime, certEndTime,
            new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic())
                    .addExtension(Extension.authorityKeyIdentifier, false,
                            extensionUtils.createAuthorityKeyIdentifier(holder))
                    .addExtension(Extension.subjectKeyIdentifier, false,
                            extensionUtils.createSubjectKeyIdentifier(entityKeyInfo))
                    .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
                    .addExtension(Extension.keyUsage, true,
                            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    if (!generalNames.isEmpty()) {
        certificateBuilder.addExtension(Extension.subjectAlternativeName, true,
                new GeneralNames(generalNames.toArray(new GeneralName[] {})));
    }

    if (crlPath != null) {
        DistributionPointName distPointOne = new DistributionPointName(
                new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath)));

        certificateBuilder.addExtension(Extension.cRLDistributionPoints, false,
                new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(distPointOne, null, null) }));
    }

    if (ocspPort != null) {
        certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod,
                new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort)));
    }

    return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer));
}

From source file:org.ccnx.ccn.impl.security.crypto.util.CryptoUtil.java

License:Open Source License

/**
 * Helper method to pull SubjectAlternativeNames from a certificate. BouncyCastle has
 * one of these, but it isn't included on all platforms. We get one by default from X509Certificate
 * but it returns us a collection of ? and we can't ever know what the ? is because we might
 * get a different impl class on different platforms. So we have to roll our own.
 * //from ww w  .  jav a2  s  .  c om
 * We filter the general names down to ones we can handle.
 * @param certificate
 * @return
 * @throws IOException 
 * @throws CertificateEncodingException 
 */
public static ArrayList<Tuple<Integer, String>> getSubjectAlternativeNames(X509Certificate certificate)
        throws IOException, CertificateEncodingException {

    byte[] encodedExtension = certificate.getExtensionValue(X509Extensions.SubjectAlternativeName.getId());

    ArrayList<Tuple<Integer, String>> list = new ArrayList<Tuple<Integer, String>>();

    if (null == encodedExtension) {
        return list;
    }

    // content of extension is wrapped in a DEROctetString
    DEROctetString content = (DEROctetString) CryptoUtil.decode(encodedExtension);
    byte[] encapsulatedOctetString = content.getOctets();

    ASN1InputStream aIn = new ASN1InputStream(encapsulatedOctetString);
    ASN1Encodable decodedObject = (ASN1Encodable) aIn.readObject();
    ASN1Sequence sequence = (ASN1Sequence) decodedObject.getDERObject();

    Integer tag;
    GeneralName generalName;

    Enumeration<?> it = sequence.getObjects();
    while (it.hasMoreElements()) {
        generalName = GeneralName.getInstance(it.nextElement());
        tag = generalName.getTagNo();

        switch (tag) {
        case GeneralName.dNSName:
        case GeneralName.rfc822Name:
        case GeneralName.uniformResourceIdentifier:
            list.add(new Tuple<Integer, String>(tag, ((DERString) generalName.getName()).getString()));
        default:
            // ignore other types
        }
    }
    return list;
}

From source file:org.ccnx.ccn.impl.security.crypto.util.CryptoUtil.java

License:Open Source License

/**
 * Get the first DNS name in the subject alternative names.
 * @throws IOException //  w ww  .  j a va  2  s .c  om
 * @throws CertificateEncodingException 
 */
public static String getSubjectAlternativeNameDNSName(X509Certificate certificate)
        throws IOException, CertificateEncodingException {
    return findSubjectAlternativeName(GeneralName.dNSName, certificate);
}

From source file:org.ccnx.ccn.impl.security.crypto.util.MinimalCertificateGenerator.java

License:Open Source License

/**
 * Both adds the server authentication OID to the EKU
 * extension, and adds the DNS name to the subject alt name
 * extension (not marked critical). (Combines addServerAuthenticationEKU and
 * addDNSNameSubjectAltName)./*from   w w w .j  a  va  2s.  com*/
 * @param serverDNSName the DNS name of the server.
 */
public void setServerAuthenticationUsage(String serverDNSName) {
    GeneralName name = new GeneralName(GeneralName.dNSName, serverDNSName);
    _subjectAltNames.add(name);
    _ekus.add(id_kp_serverAuth);
}

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

License:Open Source License

/**
 * Converts a list of encoded strings of Name Constraints into ASN1 GeneralSubtree objects.
 * This is needed when creating an BouncyCastle ASN1 NameConstraint object for inclusion
 * in a certificate.//from   w w  w.ja v  a 2  s. com
 */
public static GeneralSubtree[] toGeneralSubtrees(List<String> list) {
    if (list == null) {
        return new GeneralSubtree[0];
    }

    GeneralSubtree[] ret = new GeneralSubtree[list.size()];
    int i = 0;
    for (String entry : list) {
        int type = getNameConstraintType(entry);
        Object data = getNameConstraintData(entry);
        GeneralName genname;
        switch (type) {
        case GeneralName.dNSName:
        case GeneralName.rfc822Name:
            genname = new GeneralName(type, (String) data);
            break;
        case GeneralName.directoryName:
            genname = new GeneralName(new X500Name(CeSecoreNameStyle.INSTANCE, (String) data));
            break;
        case GeneralName.iPAddress:
            genname = new GeneralName(type, new DEROctetString((byte[]) data));
            break;
        default:
            throw new UnsupportedOperationException(
                    "Encoding of name constraint type " + type + " is not implemented.");
        }
        ret[i++] = new GeneralSubtree(genname);
    }
    return ret;
}

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

License:Open Source License

/**
 * Returns the GeneralName type code for an encoded Name Constraint.
 *//*from  www.  j  a va2  s  . c om*/
private static int getNameConstraintType(String encoded) {
    String typeString = encoded.split(":", 2)[0];
    if ("iPAddress".equals(typeString))
        return GeneralName.iPAddress;
    if ("dNSName".equals(typeString))
        return GeneralName.dNSName;
    if ("directoryName".equals(typeString))
        return GeneralName.directoryName;
    if ("rfc822Name".equals(typeString))
        return GeneralName.rfc822Name;
    throw new UnsupportedOperationException("Unsupported name constraint type " + typeString);
}

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

License:Open Source License

/**
 * Returns the GeneralName data (as a byte array or String) from an encoded string.
 *///from   w ww .j a v a2  s.  c o  m
private static Object getNameConstraintData(String encoded) {
    int type = getNameConstraintType(encoded);
    String data = encoded.split(":", 2)[1];

    switch (type) {
    case GeneralName.dNSName:
    case GeneralName.directoryName:
    case GeneralName.rfc822Name:
        return data;
    case GeneralName.iPAddress:
        try {
            return Hex.decodeHex(data.toCharArray());
        } catch (DecoderException e) {
            throw new IllegalStateException("internal name constraint data could not be decoded as hex", e);
        }
    default:
        throw new UnsupportedOperationException("Unsupported name constraint type " + type);
    }
}

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

License:Open Source License

/**
 * Formats an encoded name constraint from parseNameConstraintEntry into human-readable form.
 *//*from  w  ww . j a  va2s  .  com*/
private static String formatNameConstraintEntry(String encoded) {
    if (encoded == null) {
        return "";
    }

    int type = getNameConstraintType(encoded);
    Object data = getNameConstraintData(encoded);

    switch (type) {
    case GeneralName.dNSName:
    case GeneralName.directoryName:
        return (String) data; // not changed during encoding
    case GeneralName.iPAddress:
        byte[] bytes = (byte[]) data;
        byte[] ip = new byte[bytes.length / 2];
        byte[] netmaskBytes = new byte[bytes.length / 2];
        System.arraycopy(bytes, 0, ip, 0, ip.length);
        System.arraycopy(bytes, ip.length, netmaskBytes, 0, netmaskBytes.length);

        int netmask = 0;
        for (int i = 0; i < 8 * netmaskBytes.length; i++) {
            final boolean one = (netmaskBytes[i / 8] >> (7 - i % 8) & 1) == 1;
            if (one && netmask == i) {
                netmask++; // leading ones
            } else if (one) {
                // trailings ones = error!
                throw new IllegalArgumentException("Unsupported netmask with mixed ones/zeros");
            }
        }

        try {
            return InetAddress.getByAddress(ip).getHostAddress() + "/" + netmask;
        } catch (UnknownHostException e) {
            throw new IllegalArgumentException(e);
        }
    case GeneralName.rfc822Name:
        // Prepend @ is it's only the domain part to distinguish from DNS names
        String str = (String) data;
        return (str.contains("@") ? str : "@" + str);
    default:
        throw new UnsupportedOperationException("Unsupported name constraint type " + type);
    }
}