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

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

Introduction

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

Prototype

int rfc822Name

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

Click Source Link

Usage

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.  j  a  v  a  2  s.  co m
 * 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 email address in the subject alternative names.
 * @throws IOException /* w ww . j a v  a 2  s. c o  m*/
 * @throws CertificateEncodingException 
 */
public static String getSubjectAlternativeNameEmailAddress(X509Certificate certificate)
        throws IOException, CertificateEncodingException {
    return findSubjectAlternativeName(GeneralName.rfc822Name, certificate);
}

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

License:Open Source License

/**
 * Both adds the secure email OID to the EKU
 * extension, and adds the email address to the subject alt name
 * extension (not marked critical). (Combines addSecureEmailEKU and addEmailSubjectAltName).
 * @param subjectEmailAddress the email address of the subject.
 *///  w w  w.  j  a v a 2  s  .  co  m
public void setSecureEmailUsage(String subjectEmailAddress) {
    GeneralName name = new GeneralName(GeneralName.rfc822Name, subjectEmailAddress);
    _subjectAltNames.add(name);
    _ekus.add(id_kp_emailProtection);
}

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 . j a  v  a2 s.c  o  m
 */
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.
 *//* ww  w .j a  v a 2 s.co m*/
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 ww  w. ja va  2s  .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 w w.java  2s  .  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);
    }
}

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

License:Open Source License

/**
 * Tests the following methods://from  ww w .  ja v  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.glite.slcs.pki.CertificateExtensionFactory.java

License:eu-egee.org license

/**
 * Creates a RFC882 Subject Alternative Name: email:johndoe@example.com
 * extension./*from w w w .j a v a 2s .  c  o m*/
 * 
 * @param emailAddress
 *            The email address to be included as alternative name.
 * @return The subject alternative name CertificateExtension.
 */
static protected CertificateExtension createSubjectAltNameExtension(String emailAddress) {
    GeneralName subjectAltName = new GeneralName(GeneralName.rfc822Name, emailAddress);
    GeneralNames subjectAltNames = new GeneralNames(subjectAltName);
    X509Extension subjectAltNameExtension = new X509Extension(false, new DEROctetString(subjectAltNames));
    return new CertificateExtension(X509Extensions.SubjectAlternativeName, "SubjectAltName",
            subjectAltNameExtension, emailAddress);

}

From source file:org.glite.slcs.pki.CertificateExtensionFactory.java

License:eu-egee.org license

/**
 * /*  w  ww .  j ava2  s.  c o  m*/
 * @param prefixedAltNames
 * @param values
 * @return
 */
static protected CertificateExtension createSubjectAltNameExtension(Vector prefixedAltNames, String values) {
    ASN1EncodableVector altNames = new ASN1EncodableVector();
    Enumeration typeAndNames = prefixedAltNames.elements();
    while (typeAndNames.hasMoreElements()) {
        String typeAndName = (String) typeAndNames.nextElement();
        typeAndName = typeAndName.trim();
        if (typeAndName.startsWith("email:")) {
            String emailAddress = typeAndName.substring("email:".length());
            GeneralName altName = new GeneralName(GeneralName.rfc822Name, emailAddress);
            altNames.add(altName);

        } else if (typeAndName.startsWith("dns:")) {
            String hostname = typeAndName.substring("dns:".length());
            GeneralName altName = new GeneralName(GeneralName.dNSName, hostname);
            altNames.add(altName);
        } else {
            LOG.error("Unsupported subjectAltName: " + typeAndName);
        }
    }
    DERSequence subjectAltNames = new DERSequence(altNames);
    GeneralNames generalNames = new GeneralNames(subjectAltNames);
    X509Extension subjectAltNameExtension = new X509Extension(false, new DEROctetString(generalNames));
    return new CertificateExtension(X509Extensions.SubjectAlternativeName, "SubjectAltName",
            subjectAltNameExtension, values);

}