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

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

Introduction

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

Prototype

private GeneralNames(ASN1Sequence seq) 

Source Link

Usage

From source file:org.eclipse.milo.opcua.stack.core.util.CertificateUtil.java

License:Open Source License

/**
 * Generate a {@link PKCS10CertificationRequest} for the provided {@code certificate} and {@code keyPair}.
 *
 * @param keyPair     the {@link KeyPair} for {@code certificate}.
 * @param certificate the {@link X509Certificate} to request signing for.
 * @return a {@link PKCS10CertificationRequest}.
 * @throws Exception if creating the signing request fails for any reason.
 *///from w  w  w  . ja va2s  .  c  o  m
public static PKCS10CertificationRequest generateCsr(KeyPair keyPair, X509Certificate certificate)
        throws Exception {

    PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
            certificate.getSubjectX500Principal(), certificate.getPublicKey());

    GeneralNames subjectAltNames = new GeneralNames(
            getSubjectAltNames(certificate).toArray(new GeneralName[0]));

    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(certificate.getSigAlgName());

    ContentSigner signer = signerBuilder.build(keyPair.getPrivate());

    return builder.build(signer);
}

From source file:org.eclipse.milo.opcua.stack.core.util.CertificateUtil.java

License:Open Source License

/**
 * Generate a {@link PKCS10CertificationRequest}.
 *
 * @param keyPair            the {@link KeyPair} containing Public and Private keys.
 * @param subject            the subject name {@link X500Name}.
 * @param sanUri             the URI to request in the SAN.
 * @param sanDnsNames        the DNS names to request in the SAN.
 * @param sanIpAddresses     the IP addresses to request in the SAN.
 * @param signatureAlgorithm the signature algorithm to use when generating the signature to validate the
 *                           certificate.
 * @return a {@link PKCS10CertificationRequest}.
 * @throws Exception if creating the signing request fails for any reason.
 *///from  w  ww.ja  v  a  2  s. c o m
public static PKCS10CertificationRequest generateCsr(KeyPair keyPair, X500Name subject, String sanUri,
        List<String> sanDnsNames, List<String> sanIpAddresses, String signatureAlgorithm) throws Exception {

    PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(subject,
            SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    List<GeneralName> generalNames = new ArrayList<>();

    generalNames.add(new GeneralName(SUBJECT_ALT_NAME_URI, sanUri));

    sanDnsNames.stream().map(n -> new GeneralName(SUBJECT_ALT_NAME_DNS_NAME, n)).forEach(generalNames::add);

    sanIpAddresses.stream().map(n -> new GeneralName(SUBJECT_ALT_NAME_IP_ADDRESS, n))
            .forEach(generalNames::add);

    ExtensionsGenerator extGen = new ExtensionsGenerator();

    extGen.addExtension(Extension.subjectAlternativeName, false,
            new GeneralNames(generalNames.toArray(new GeneralName[0])));

    builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);

    ContentSigner signer = signerBuilder.build(keyPair.getPrivate());

    return builder.build(signer);
}

From source file:org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator.java

License:Open Source License

protected void addSubjectAlternativeNames(X509v3CertificateBuilder certificateBuilder, KeyPair keyPair,
        @Nullable String applicationUri, List<String> dnsNames, List<String> ipAddresses)
        throws CertIOException, NoSuchAlgorithmException {

    List<GeneralName> generalNames = new ArrayList<>();

    if (applicationUri != null) {
        generalNames.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri));
    }/*w  w w . ja  v  a  2 s  .co  m*/

    dnsNames.stream().distinct().map(s -> new GeneralName(GeneralName.dNSName, s)).forEach(generalNames::add);

    ipAddresses.stream().distinct().map(s -> new GeneralName(GeneralName.iPAddress, s))
            .forEach(generalNames::add);

    certificateBuilder.addExtension(Extension.subjectAlternativeName, false,
            new GeneralNames(generalNames.toArray(new GeneralName[] {})));

    // Subject Key Identifier
    certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
            new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));
}

From source file:org.ejbca.core.model.ca.caadmin.X509CA.java

License:Open Source License

/** Generate a list of Distribution points.
 * @param distPoints distribution points as String in semi column (';') separated format.
 * @return list of distribution points.//from  w  w w  . j  a  v a 2  s . c o  m
 */
private List<DistributionPoint> generateDistributionPoints(String distPoints) {
    if (distPoints == null) {
        distPoints = "";
    }
    // Multiple CDPs are separated with the ';' sign
    Iterator<String> it = StringTools.splitURIs(distPoints).iterator();
    ArrayList<DistributionPoint> result = new ArrayList<DistributionPoint>();
    while (it.hasNext()) {
        String uri = (String) it.next();
        GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(uri));
        if (log.isDebugEnabled()) {
            log.debug("Added CRL distpoint: " + uri);
        }
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(gn);
        GeneralNames gns = new GeneralNames(new DERSequence(vec));
        DistributionPointName dpn = new DistributionPointName(0, gns);
        result.add(new DistributionPoint(dpn, null, null));
    }
    return result;
}

From source file:org.ejbca.core.model.ca.certextensions.standard.CrlDistributionPoints.java

License:Open Source License

@Override
public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile,
        final PublicKey userPublicKey, final PublicKey caPublicKey)
        throws CertificateExtentionConfigurationException, CertificateExtensionException {
    String crldistpoint = certProfile.getCRLDistributionPointURI();
    String crlissuer = certProfile.getCRLIssuer();
    final X509CA x509ca = (X509CA) ca;
    if (certProfile.getUseDefaultCRLDistributionPoint()) {
        crldistpoint = x509ca.getDefaultCRLDistPoint();
        crlissuer = x509ca.getDefaultCRLIssuer();
    }//from ww  w.j  a v  a 2  s  . co  m
    // Multiple CDPs are separated with the ';' sign                        
    final ArrayList<DistributionPointName> dpns = new ArrayList<DistributionPointName>();
    if (StringUtils.isNotEmpty(crldistpoint)) {
        final Iterator<String> it = StringTools.splitURIs(crldistpoint).iterator();
        while (it.hasNext()) {
            // 6 is URI
            final String uri = (String) it.next();
            final GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier,
                    new DERIA5String(uri));
            if (log.isDebugEnabled()) {
                log.debug("Added CRL distpoint: " + uri);
            }
            final ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(gn);
            final GeneralNames gns = new GeneralNames(new DERSequence(vec));
            final DistributionPointName dpn = new DistributionPointName(0, gns);
            dpns.add(dpn);
        }
    }
    // CRL issuer works much like Dist point URI. If separated by ; it is put in the same global distPoint as the URI, 
    // if there is more of one of them, the one with more is put in an own global distPoint.
    final ArrayList<GeneralNames> issuers = new ArrayList<GeneralNames>();
    if (StringUtils.isNotEmpty(crlissuer)) {
        final StringTokenizer tokenizer = new StringTokenizer(crlissuer, ";", false);
        while (tokenizer.hasMoreTokens()) {
            final String issuer = tokenizer.nextToken();
            final GeneralName gn = new GeneralName(new X509Name(issuer));
            if (log.isDebugEnabled()) {
                log.debug("Added CRL issuer: " + issuer);
            }
            final ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(gn);
            final GeneralNames gns = new GeneralNames(new DERSequence(vec));
            issuers.add(gns);
        }
    }
    final ArrayList<DistributionPoint> distpoints = new ArrayList<DistributionPoint>();
    if ((!issuers.isEmpty()) || (!dpns.isEmpty())) {
        int i = dpns.size();
        if (issuers.size() > i) {
            i = issuers.size();
        }
        for (int j = 0; j < i; j++) {
            DistributionPointName dpn = null;
            GeneralNames issuer = null;
            if (dpns.size() > j) {
                dpn = (DistributionPointName) dpns.get(j);
            }
            if (issuers.size() > j) {
                issuer = (GeneralNames) issuers.get(j);
            }
            if ((dpn != null) || (issuer != null)) {
                distpoints.add(new DistributionPoint(dpn, null, issuer));
            }
        }
    }
    CRLDistPoint ret = null;
    if (!distpoints.isEmpty()) {
        ret = new CRLDistPoint(
                (DistributionPoint[]) distpoints.toArray(new DistributionPoint[distpoints.size()]));
    }
    if (ret == null) {
        log.error("DrlDistributionPoints missconfigured, no distribution points available.");
    }
    return ret;
}

From source file:org.ejbca.core.model.ca.certextensions.standard.FreshestCrl.java

License:Open Source License

@Override
public DEREncodable getValue(final UserDataVO subject, final CA ca, final CertificateProfile certProfile,
        final PublicKey userPublicKey, final PublicKey caPublicKey)
        throws CertificateExtentionConfigurationException, CertificateExtensionException {
    String freshestcrldistpoint = certProfile.getFreshestCRLURI();
    final X509CA x509ca = (X509CA) ca;
    if (certProfile.getUseCADefinedFreshestCRL()) {
        freshestcrldistpoint = x509ca.getCADefinedFreshestCRL();
    }//from   www. j ava2 s.c o m
    // Multiple FCDPs are separated with the ';' sign
    CRLDistPoint ret = null;
    if (freshestcrldistpoint != null) {
        final StringTokenizer tokenizer = new StringTokenizer(freshestcrldistpoint, ";", false);
        final ArrayList<DistributionPoint> distpoints = new ArrayList<DistributionPoint>();
        while (tokenizer.hasMoreTokens()) {
            final String uri = tokenizer.nextToken();
            final GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier,
                    new DERIA5String(uri));
            if (log.isDebugEnabled()) {
                log.debug("Added freshest CRL distpoint: " + uri);
            }
            final ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(gn);
            final GeneralNames gns = new GeneralNames(new DERSequence(vec));
            final DistributionPointName dpn = new DistributionPointName(0, gns);
            distpoints.add(new DistributionPoint(dpn, null, null));
        }
        if (!distpoints.isEmpty()) {
            ret = new CRLDistPoint(
                    (DistributionPoint[]) distpoints.toArray(new DistributionPoint[distpoints.size()]));
        }
    }
    if (ret == null) {
        log.error("UseFreshestCRL is true, but no URI string defined!");
    }
    return ret;
}

From source file:org.ejbca.util.CertTools.java

License:Open Source License

/**
 * From an altName string as defined in getSubjectAlternativeName 
 * @param altName/*  w  w  w.j ava  2 s .c  o m*/
 * @return ASN.1 GeneralNames
 * @see #getSubjectAlternativeName
 */
public static GeneralNames getGeneralNamesFromAltName(String altName) {
    if (log.isTraceEnabled()) {
        log.trace(">getGeneralNamesFromAltName: " + altName);
    }
    ASN1EncodableVector vec = new ASN1EncodableVector();

    ArrayList<String> emails = CertTools.getEmailFromDN(altName);
    if (!emails.isEmpty()) {
        Iterator<String> iter = emails.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(1, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    ArrayList<String> dns = CertTools.getPartsFromDN(altName, CertTools.DNS);
    if (!dns.isEmpty()) {
        Iterator<String> iter = dns.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(2, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    String directoryName = getDirectoryStringFromAltName(altName);
    if (directoryName != null) {
        X509Name x509DirectoryName = new X509Name(directoryName);
        GeneralName gn = new GeneralName(4, x509DirectoryName);
        vec.add(gn);
    }

    ArrayList<String> uri = CertTools.getPartsFromDN(altName, CertTools.URI);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }
    uri = CertTools.getPartsFromDN(altName, CertTools.URI1);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }
    uri = CertTools.getPartsFromDN(altName, CertTools.URI2);
    if (!uri.isEmpty()) {
        Iterator<String> iter = uri.iterator();
        while (iter.hasNext()) {
            GeneralName gn = new GeneralName(6, new DERIA5String((String) iter.next()));
            vec.add(gn);
        }
    }

    ArrayList<String> ipstr = CertTools.getPartsFromDN(altName, CertTools.IPADDR);
    if (!ipstr.isEmpty()) {
        Iterator<String> iter = ipstr.iterator();
        while (iter.hasNext()) {
            byte[] ipoctets = StringTools.ipStringToOctets((String) iter.next());
            GeneralName gn = new GeneralName(7, new DEROctetString(ipoctets));
            vec.add(gn);
        }
    }

    // UPN is an OtherName see method getUpn... for asn.1 definition
    ArrayList<String> upn = CertTools.getPartsFromDN(altName, CertTools.UPN);
    if (!upn.isEmpty()) {
        Iterator<String> iter = upn.iterator();
        while (iter.hasNext()) {
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERObjectIdentifier(CertTools.UPN_OBJECTID));
            v.add(new DERTaggedObject(true, 0, new DERUTF8String((String) iter.next())));
            //GeneralName gn = new GeneralName(new DERSequence(v), 0);
            DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        }
    }

    ArrayList<String> guid = CertTools.getPartsFromDN(altName, CertTools.GUID);
    if (!guid.isEmpty()) {
        Iterator<String> iter = guid.iterator();
        while (iter.hasNext()) {
            ASN1EncodableVector v = new ASN1EncodableVector();
            byte[] guidbytes = Hex.decode((String) iter.next());
            if (guidbytes != null) {
                v.add(new DERObjectIdentifier(CertTools.GUID_OBJECTID));
                v.add(new DERTaggedObject(true, 0, new DEROctetString(guidbytes)));
                DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
                vec.add(gn);
            } else {
                log.error("Cannot decode hexadecimal guid: " + guid);
            }
        }
    }

    // Krb5PrincipalName is an OtherName, see method getKrb5Principal...for ASN.1 definition
    ArrayList<String> krb5principalname = CertTools.getPartsFromDN(altName, CertTools.KRB5PRINCIPAL);
    if (!krb5principalname.isEmpty()) {
        Iterator<String> iter = krb5principalname.iterator();
        while (iter.hasNext()) {
            // Start by parsing the input string to separate it in different parts
            String principalString = (String) iter.next();
            if (log.isDebugEnabled()) {
                log.debug("principalString: " + principalString);
            }
            // The realm is the last part moving back until an @
            int index = principalString.lastIndexOf('@');
            String realm = "";
            if (index > 0) {
                realm = principalString.substring(index + 1);
            }
            if (log.isDebugEnabled()) {
                log.debug("realm: " + realm);
            }
            // Now we can have several principals separated by /
            ArrayList<String> principalarr = new ArrayList<String>();
            int jndex = 0;
            int bindex = 0;
            while (jndex < index) {
                // Loop and add all strings separated by /
                jndex = principalString.indexOf('/', bindex);
                if (jndex == -1) {
                    jndex = index;
                }
                String s = principalString.substring(bindex, jndex);
                if (log.isDebugEnabled()) {
                    log.debug("adding principal name: " + s);
                }
                principalarr.add(s);
                bindex = jndex + 1;
            }

            // Now we must construct the rather complex asn.1...
            ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName
            v.add(new DERObjectIdentifier(CertTools.KRB5PRINCIPAL_OBJECTID));

            // First the Krb5PrincipalName sequence
            ASN1EncodableVector krb5p = new ASN1EncodableVector();
            // The realm is the first tagged GeneralString
            krb5p.add(new DERTaggedObject(true, 0, new DERGeneralString(realm)));
            // Second is the sequence of principal names, which is at tagged position 1 in the krb5p 
            ASN1EncodableVector principals = new ASN1EncodableVector();
            // According to rfc4210 the type NT-UNKNOWN is 0, and according to some other rfc this type should be used...
            principals.add(new DERTaggedObject(true, 0, new DERInteger(0)));
            // The names themselves are yet another sequence
            Iterator<String> i = principalarr.iterator();
            ASN1EncodableVector names = new ASN1EncodableVector();
            while (i.hasNext()) {
                String principalName = (String) i.next();
                names.add(new DERGeneralString(principalName));
            }
            principals.add(new DERTaggedObject(true, 1, new DERSequence(names)));
            krb5p.add(new DERTaggedObject(true, 1, new DERSequence(principals)));

            v.add(new DERTaggedObject(true, 0, new DERSequence(krb5p)));
            DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
            vec.add(gn);
        }
    }

    // To support custom OIDs in altNames, they must be added as an OtherName of plain type UTF8String
    ArrayList<String> customoids = CertTools.getCustomOids(altName);
    if (!customoids.isEmpty()) {
        Iterator<String> iter = customoids.iterator();
        while (iter.hasNext()) {
            String oid = (String) iter.next();
            ArrayList<String> oidval = CertTools.getPartsFromDN(altName, oid);
            if (!oidval.isEmpty()) {
                Iterator<String> valiter = oidval.iterator();
                while (valiter.hasNext()) {
                    ASN1EncodableVector v = new ASN1EncodableVector();
                    v.add(new DERObjectIdentifier(oid));
                    v.add(new DERTaggedObject(true, 0, new DERUTF8String((String) valiter.next())));
                    DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));
                    vec.add(gn);
                }
            }
        }
    }

    GeneralNames ret = null;
    if (vec.size() > 0) {
        ret = new GeneralNames(new DERSequence(vec));
    }
    return ret;
}

From source file:org.elasticsearch.xpack.core.ssl.CertGenUtils.java

License:Open Source License

/**
 * Converts the {@link InetAddress} objects into a {@link GeneralNames} object that is used to represent subject alternative names.
 *//*w w w.j a  va  2s  . co m*/
public static GeneralNames getSubjectAlternativeNames(boolean resolveName, Set<InetAddress> addresses)
        throws SocketException {
    Set<GeneralName> generalNameList = new HashSet<>();
    for (InetAddress address : addresses) {
        if (address.isAnyLocalAddress()) {
            // it is a wildcard address
            for (InetAddress inetAddress : InetAddressHelper.getAllAddresses()) {
                addSubjectAlternativeNames(resolveName, inetAddress, generalNameList);
            }
        } else {
            addSubjectAlternativeNames(resolveName, address, generalNameList);
        }
    }
    return new GeneralNames(generalNameList.toArray(new GeneralName[generalNameList.size()]));
}

From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateTool.java

License:Open Source License

private static GeneralNames getSubjectAlternativeNamesValue(List<String> ipAddresses, List<String> dnsNames,
        List<String> commonNames) {
    Set<GeneralName> generalNameList = new HashSet<>();
    for (String ip : ipAddresses) {
        generalNameList.add(new GeneralName(GeneralName.iPAddress, ip));
    }//from  w ww  .  j  a va 2s  .co m

    for (String dns : dnsNames) {
        generalNameList.add(new GeneralName(GeneralName.dNSName, dns));
    }

    for (String cn : commonNames) {
        generalNameList.add(CertGenUtils.createCommonName(cn));
    }

    if (generalNameList.isEmpty()) {
        return null;
    }
    return new GeneralNames(generalNameList.toArray(new GeneralName[0]));
}

From source file:org.glite.security.util.proxy.ProxyTracingExtension.java

License:Apache License

/**
 * Generates a new proxy tracing item from the URL.
 * /*from   ww w .  j a va 2 s . c om*/
 * @param url The URL to identify the issuer or the subject.
 */
public ProxyTracingExtension(String url) {
    m_name = new GeneralName(GeneralName.uniformResourceIdentifier, url);
    m_names = new GeneralNames(m_name);
}