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:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

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

    List<String> dnsNames = 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.dNSName) {
                    dnsNames.add(((DERIA5String) name.getName()).getString());
                }//from  w ww .  j a v  a2  s .co m
            }
        }
    }
    return dnsNames;
}

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

License:Apache License

public static List<String> extractX509CertDnsNames(X509Certificate x509Cert) {
    Collection<List<?>> altNames = null;
    try {/*from   w  w w  .  j  a  v a2s.c  o m*/
        altNames = x509Cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException ex) {
        LOG.error("extractX509IPAddresses: Caught CertificateParsingException when parsing certificate: "
                + ex.getMessage());
    }

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

    List<String> dnsNames = 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.dNSName) {
            dnsNames.add((String) item.get(1));
        }
    }
    return dnsNames;
}

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);/*  w  w w .  j  ava2  s.co 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:com.yahoo.athenz.example.instance.InstanceClientRefresh.java

License:Apache License

public static String generateCSR(String domainName, String serviceName, String instanceId, String dnsSuffix,
        PrivateKey key) {//from   w  w w .  j  av a2 s  .  co  m

    final String dn = "cn=" + domainName + "." + serviceName + ",o=Athenz";

    // now let's generate our dsnName field based on our principal's details

    StringBuilder dnsName = new StringBuilder(128);
    dnsName.append(serviceName);
    dnsName.append('.');
    dnsName.append(domainName.replace('.', '-'));
    dnsName.append('.');
    dnsName.append(dnsSuffix);

    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName.toString()));

    // next we include our instance id

    StringBuilder dnsInstance = new StringBuilder(128);
    dnsInstance.append(instanceId);
    dnsInstance.append(".instanceid.athenz.");
    dnsInstance.append(dnsSuffix);

    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsInstance.toString()));

    String csr = null;
    try {
        csr = Crypto.generateX509CSR(key, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        System.err.println(ex.getMessage());
    }

    return csr;
}

From source file:com.yahoo.athenz.zts.ZTSClient.java

License:Apache License

/**
 * Generate a Role Certificate request that could be sent to ZTS
 * to obtain a X509 Certificate for the requested role.
 * @param principalDomain name of the principal's domain
 * @param principalService name of the principal's service
 * @param roleDomainName name of the domain where role is defined
 * @param roleName name of the role to get a certificate request for
 * @param privateKey private key for the service identity for the caller
 * @param csrDn string identifying the dn for the csr without the cn component
 * @param csrDomain string identifying the dns domain for generating SAN fields
 * @param expiryTime number of seconds to request certificate to be valid for
 * @return RoleCertificateRequest object
 *//*from w ww  .  j ava 2 s.  co  m*/
static public RoleCertificateRequest generateRoleCertificateRequest(final String principalDomain,
        final String principalService, final String roleDomainName, final String roleName,
        PrivateKey privateKey, final String csrDn, final String csrDomain, int expiryTime) {

    if (principalDomain == null || principalService == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }

    if (roleDomainName == null || roleName == null) {
        throw new IllegalArgumentException("Role DomainName and Name must be specified");
    }

    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }

    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be our role resource value

    final String domain = principalDomain.toLowerCase();
    final String service = principalService.toLowerCase();

    String dn = "cn=" + roleDomainName.toLowerCase() + ":role." + roleName.toLowerCase();
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }

    // now let's generate our dsnName and email fields which will based on
    // our principal's details

    StringBuilder hostBuilder = new StringBuilder(128);
    hostBuilder.append(service);
    hostBuilder.append('.');
    hostBuilder.append(domain.replace('.', '-'));
    hostBuilder.append('.');
    hostBuilder.append(csrDomain);
    String hostName = hostBuilder.toString();

    String email = domain + "." + service + "@" + csrDomain;

    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));
    sanArray[1] = new GeneralName(GeneralName.rfc822Name, new DERIA5String(email));

    String csr = null;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    RoleCertificateRequest req = new RoleCertificateRequest().setCsr(csr)
            .setExpiryTime(Long.valueOf(expiryTime));
    return req;
}

From source file:com.yahoo.athenz.zts.ZTSClient.java

License:Apache License

/**
 * Generate a Instance Refresh request that could be sent to ZTS to
 * request a TLS certificate for a service.
 * @param principalDomain name of the principal's domain
 * @param principalService name of the principal's service
 * @param privateKey private key for the service identity for the caller
 * @param csrDn string identifying the dn for the csr without the cn component
 * @param csrDomain string identifying the dns domain for generating SAN fields
 * @param expiryTime number of seconds to request certificate to be valid for
 * @return InstanceRefreshRequest object
 *//*from ww w  .  j a v  a  2 s  .co  m*/
static public InstanceRefreshRequest generateInstanceRefreshRequest(final String principalDomain,
        final String principalService, PrivateKey privateKey, final String csrDn, final String csrDomain,
        int expiryTime) {

    if (principalDomain == null || principalService == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }

    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }

    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be based on our service name

    final String domain = principalDomain.toLowerCase();
    final String service = principalService.toLowerCase();
    final String cn = domain + "." + service;

    String dn = "cn=" + cn;
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }

    // now let's generate our dsnName field based on our principal's details

    StringBuilder hostBuilder = new StringBuilder(128);
    hostBuilder.append(service);
    hostBuilder.append('.');
    hostBuilder.append(domain.replace('.', '-'));
    hostBuilder.append('.');
    hostBuilder.append(csrDomain);
    String hostName = hostBuilder.toString();

    GeneralName[] sanArray = new GeneralName[1];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));

    String csr = null;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    InstanceRefreshRequest req = new InstanceRefreshRequest().setCsr(csr)
            .setExpiryTime(Integer.valueOf(expiryTime));
    return req;
}

From source file:com.yahoo.athenz.zts.ZTSClient.java

License:Apache License

/**
 * For AWS Lambda functions generate a new private key, request a
 * x.509 certificate based on the requested CSR and return both to
 * the client in order to establish tls connections with other
 * Athenz enabled services.//from   w ww  .  j  a v  a 2  s .co m
 * @param domainName name of the domain
 * @param serviceName name of the service
 * @param account AWS account name that the function runs in
 * @param provider name of the provider service for AWS Lambda
 * @return AWSLambdaIdentity with private key and certificate
 */
public AWSLambdaIdentity getAWSLambdaServiceCertificate(String domainName, String serviceName, String account,
        String provider) {

    if (domainName == null || serviceName == null) {
        throw new IllegalArgumentException("Domain and Service must be specified");
    }

    if (account == null || provider == null) {
        throw new IllegalArgumentException("AWS Account and Provider must be specified");
    }

    if (x509CsrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }

    // first we're going to generate a private key for the request

    AWSLambdaIdentity lambdaIdentity = new AWSLambdaIdentity();
    try {
        lambdaIdentity.setPrivateKey(Crypto.generateRSAPrivateKey(2048));
    } catch (CryptoException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    // we need to generate an csr with an instance register object

    InstanceRegisterInformation info = new InstanceRegisterInformation();
    info.setDomain(domainName.toLowerCase());
    info.setService(serviceName.toLowerCase());
    info.setProvider(provider.toLowerCase());

    final String athenzService = info.getDomain() + "." + info.getService();

    // generate our dn which will be based on our service name

    StringBuilder dnBuilder = new StringBuilder(128);
    dnBuilder.append("cn=");
    dnBuilder.append(athenzService);
    if (x509CsrDn != null) {
        dnBuilder.append(',');
        dnBuilder.append(x509CsrDn);
    }

    // now let's generate our dsnName field based on our principal's details

    StringBuilder hostBuilder = new StringBuilder(128);
    hostBuilder.append(info.getService());
    hostBuilder.append('.');
    hostBuilder.append(info.getDomain().replace('.', '-'));
    hostBuilder.append('.');
    hostBuilder.append(x509CsrDomain);

    StringBuilder instanceHostBuilder = new StringBuilder(128);
    instanceHostBuilder.append("lambda-");
    instanceHostBuilder.append(account);
    instanceHostBuilder.append('-');
    instanceHostBuilder.append(info.getService());
    instanceHostBuilder.append(".instanceid.athenz.");
    instanceHostBuilder.append(x509CsrDomain);

    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostBuilder.toString()));
    sanArray[1] = new GeneralName(GeneralName.dNSName, new DERIA5String(instanceHostBuilder.toString()));

    // next generate the csr based on our private key and data

    try {
        info.setCsr(Crypto.generateX509CSR(lambdaIdentity.getPrivateKey(), dnBuilder.toString(), sanArray));
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    // finally obtain attestation data for lambda

    info.setAttestationData(getAWSLambdaAttestationData(athenzService, account));

    // request the x.509 certificate from zts server

    Map<String, List<String>> responseHeaders = new HashMap<>();
    InstanceIdentity identity = postInstanceRegisterInformation(info, responseHeaders);

    try {
        lambdaIdentity.setX509Certificate(Crypto.loadX509Certificate(identity.getX509Certificate()));
    } catch (CryptoException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }

    return lambdaIdentity;
}

From source file:com.zimbra.cs.service.authenticator.CertUtil.java

License:Open Source License

private void printSubjectAlternativeNames(PrintStream outStream) throws Exception {

    final String UPN_DISPLAY = "Principal Name";
    final String RFC822NAME_DISPLAY = "RFC822 Name";
    final String DNSNAME_DISPLAY = "DNS Name";

    outStream.format("X509v3 Subject Alternative Name: \n");

    ASN1InputStream decoder = null;
    try {//w ww.  j  av  a  2  s  . co  m
        Collection<List<?>> generalNames = cert.getSubjectAlternativeNames();
        // Check that the certificate includes the SubjectAltName extension
        if (generalNames == null) {
            return;
        }

        /*
           OtherName ::= SEQUENCE {
          type-id    OBJECT IDENTIFIER,
          value      [0] EXPLICIT ANY DEFINED BY type-id }
         */

        for (List<?> generalName : generalNames) {
            Integer tag = (Integer) generalName.get(0);
            if (GeneralName.otherName == tag.intValue()) {
                // Value is encoded using ASN.1
                decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]);
                DEREncodable encoded = decoder.readObject();
                DERSequence derSeq = (DERSequence) encoded;

                DERObjectIdentifier typeId = DERObjectIdentifier.getInstance(derSeq.getObjectAt(0));
                String oid = typeId.getId();

                String value = null;
                ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1));
                if (OID_UPN.equals(oid)) {
                    ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject());
                    DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject());
                    value = str.getString();
                }

                outStream.format("    [%d] %s(%s) = %s\n", tag, oid, UPN_DISPLAY, value);
            } else if (GeneralName.rfc822Name == tag.intValue()) {
                String value = (String) generalName.get(1);
                outStream.format("    [%d] %s = %s\n", tag, RFC822NAME_DISPLAY, value);
            } else if (GeneralName.dNSName == tag.intValue()) {
                String value = (String) generalName.get(1);
                outStream.format("    [%d] %s = %s\n", tag, DNSNAME_DISPLAY, value);
            } else {
                outStream.format("    [%d] - not yet supported\n", tag);
            }

        }
    } catch (CertificateParsingException e) {
        e.printStackTrace();
    } finally {
        ByteUtil.closeStream(decoder);
    }
}

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

/**
 * Converts the tag no of a general name to a human readable value
 *///  w  w  w  .  j a  va 2  s  .c o  m
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 ("");
}

From source file:edu.washington.iam.tools.IamCertificateHelper.java

License:Apache License

public static int parseCsr(IamCertificate cert) throws IamCertificateException {

    try {//from  w w w. jav a 2s  .c  om
        PEMReader pRd = new PEMReader(new StringReader(cert.pemRequest));
        PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject();
        if (request == null)
            throw new IamCertificateException("invalid CSR (request)");
        CertificationRequestInfo info = request.getCertificationRequestInfo();
        if (info == null)
            throw new IamCertificateException("invalid CSR (info)");

        X509Name dn = info.getSubject();
        if (dn == null)
            throw new IamCertificateException("invalid CSR (dn)");
        log.debug("dn=" + dn.toString());
        cert.dn = dn.toString();
        try {
            List cns = dn.getValues(X509Name.CN);
            cert.cn = (String) (cns.get(0));
            log.debug("cn=" + cert.cn);
            cert.names.add(cert.cn); // first entry for names is always cn
            cns = dn.getValues(X509Name.C);
            cert.dnC = (String) (cns.get(0));
            cns = dn.getValues(X509Name.ST);
            cert.dnST = (String) (cns.get(0));
        } catch (Exception e) {
            log.debug("get cn error: " + e);
            throw new IamCertificateException("invalid CSR");
        }

        // see if we've got alt names (in extensions)

        ASN1Set attrs = info.getAttributes();
        if (attrs != null) {
            for (int a = 0; a < attrs.size(); a++) {
                Attribute attr = Attribute.getInstance(attrs.getObjectAt(a));
                if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {

                    // is the extension
                    X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

                    // get the subAltName extension
                    DERObjectIdentifier sanoid = new DERObjectIdentifier(
                            X509Extensions.SubjectAlternativeName.getId());
                    X509Extension xext = extensions.getExtension(sanoid);
                    if (xext != null) {
                        log.debug("processing altname extensions");
                        ASN1Object asn1 = X509Extension.convertValueToObject(xext);
                        Enumeration dit = DERSequence.getInstance(asn1).getObjects();
                        while (dit.hasMoreElements()) {
                            GeneralName gn = GeneralName.getInstance(dit.nextElement());
                            log.debug("altname tag=" + gn.getTagNo());
                            log.debug("altname name=" + gn.getName().toString());
                            if (gn.getTagNo() == GeneralName.dNSName)
                                cert.names.add(gn.getName().toString());
                        }
                    }

                }
            }
        }

        // check key size
        PublicKey pk = request.getPublicKey();
        log.debug("key alg = " + pk.getAlgorithm());
        log.debug("key fmt = " + pk.getFormat());
        if (pk.getAlgorithm().equals("RSA")) {
            RSAPublicKey rpk = (RSAPublicKey) pk;
            cert.keySize = rpk.getModulus().bitLength();
            log.debug("key size = " + cert.keySize);
        }

    } catch (IOException e) {
        log.debug("ioerror: " + e);
        throw new IamCertificateException("invalid CSR " + e.getMessage());
    } catch (Exception e) {
        log.debug("excp: " + e);
        throw new IamCertificateException("invalid CSR");
    }
    return 1;
}