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:gui.ExtensionsPopup.java

private void addIssuerAltNameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addIssuerAltNameButtonActionPerformed
    String extension = issuerAltNameTextField.getText();
    issuerAltNameTextField.setText("");
    if (!extension.isEmpty()) {
        String extName = (String) issuerAltNameComboBox.getSelectedItem();
        try {/*from   w w w  .  j a v a  2  s.  co  m*/
            switch (extName) {
            case "Other Name":
                generalNamesBuilder.addName(new GeneralName(GeneralName.otherName, extension));
                break;
            case "RFC822 Name":
                generalNamesBuilder.addName(new GeneralName(GeneralName.rfc822Name, extension));
                break;
            case "DNS Name":
                generalNamesBuilder.addName(new GeneralName(GeneralName.dNSName, extension));
                break;
            case "x400 Address":
                generalNamesBuilder.addName(new GeneralName(GeneralName.x400Address, extension));
                break;
            case "Directory Name":
                generalNamesBuilder
                        .addName(new GeneralName(GeneralName.directoryName, new X500Name(extension)));
                break;
            case "EDI Party Name":
                generalNamesBuilder.addName(new GeneralName(GeneralName.ediPartyName, extension));
                break;
            case "URI":
                generalNamesBuilder.addName(new GeneralName(GeneralName.uniformResourceIdentifier, extension));
                break;
            case "IP Address":
                generalNamesBuilder.addName(new GeneralName(GeneralName.iPAddress, extension));
                break;
            case "Registered ID":
                generalNamesBuilder.addName(new GeneralName(GeneralName.registeredID, extension));
                break;
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, Errors.EXTENSION_INVALID_FORMAT, "Error",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        issuerAltNameTextArea.append(extName + ": " + extension + "\n");
    }
}

From source file:io.spikex.core.Main.java

License:Apache License

private void createKeyStore(final YamlDocument conf) {

    YamlDocument confKeyStore = conf.getDocument(CONF_KEY_KEYSTORE);
    boolean generate = confKeyStore.getValue(CONF_KEY_GENERATE, DEF_GENERATE_KEYSTORE);

    if (generate) {

        Path keyStorePath = Paths
                .get(confKeyStore.getValue(CONF_KEY_PATH, m_confPath.resolve(DEF_KEYSTORE_PATH).toString()))
                .toAbsolutePath().normalize();

        if (!Files.exists(keyStorePath)) {

            Provider bcProvider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
            if (bcProvider == null) {
                Security.addProvider(new BouncyCastleProvider());
            }//from ww w  . j  a v  a 2s  . c  om

            String password = confKeyStore.getValue(CONF_KEY_PASSWORD, DEF_KEYSTORE_PASSWORD);
            String hostFqdn = confKeyStore.getValue(CONF_KEY_HOST_FQDN, HostOs.hostName());
            List<String> subjAltNames = confKeyStore.getValue(CONF_KEY_SUBJECT_ALT_NAME, new ArrayList());

            try (FileOutputStream out = new FileOutputStream(keyStorePath.toFile())) {

                m_logger.info("Generating keystore: {}", keyStorePath);

                KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA",
                        BouncyCastleProvider.PROVIDER_NAME);

                SecureRandom rnd = new SecureRandom();
                generator.initialize(2048, rnd);
                KeyPair pair = generator.generateKeyPair();

                // DN
                X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
                nameBuilder.addRDN(BCStyle.C, System.getProperty("user.country.format", "NU"));
                nameBuilder.addRDN(BCStyle.OU, "Self-signed test certificate");
                nameBuilder.addRDN(BCStyle.OU, "For testing purposes only");
                nameBuilder.addRDN(BCStyle.O, "Spike.x");
                nameBuilder.addRDN(BCStyle.CN, hostFqdn);

                long oneDay = 24 * 60 * 60 * 1000;
                Date notBefore = new Date(System.currentTimeMillis() - oneDay); // Yesterday
                Date notAfter = new Date(System.currentTimeMillis() + (oneDay * 3 * 365)); // 3 years

                BigInteger serialNum = BigInteger.valueOf(rnd.nextLong());
                X509v3CertificateBuilder x509v3Builder = new JcaX509v3CertificateBuilder(nameBuilder.build(),
                        serialNum, notBefore, notAfter, nameBuilder.build(), pair.getPublic());

                //
                // Extensions
                //
                x509v3Builder.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
                x509v3Builder.addExtension(X509Extensions.KeyUsage, true,
                        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
                x509v3Builder.addExtension(X509Extensions.ExtendedKeyUsage, true,
                        new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

                GeneralName[] dnsNames = new GeneralName[subjAltNames.size()];
                for (int i = 0; i < subjAltNames.size(); i++) {
                    String name = subjAltNames.get(i);
                    m_logger.info("Adding subject alt name: {}", name);
                    dnsNames[i] = new GeneralName(GeneralName.dNSName, name);
                }
                x509v3Builder.addExtension(X509Extensions.SubjectAlternativeName, false,
                        new GeneralNames(dnsNames));

                ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(pair.getPrivate());

                X509Certificate cert = new JcaX509CertificateConverter()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .getCertificate(x509v3Builder.build(signer));

                // Validate
                cert.checkValidity(new Date());
                cert.verify(cert.getPublicKey());

                // Save in keystore
                KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(null);
                ks.setKeyEntry(hostFqdn, pair.getPrivate(), password.toCharArray(), new Certificate[] { cert });

                m_logger.info("Created self-signed certificate: {}", hostFqdn);
                ks.store(out, password.toCharArray());

            } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
                    | NoSuchProviderException | OperatorCreationException | InvalidKeyException
                    | SignatureException e) {
                throw new RuntimeException("Failed to create keystore: " + keyStorePath, e);
            }
        }
    }
}

From source file:it.zero11.acme.utils.X509Utils.java

License:Apache License

public static PKCS10CertificationRequest generateCSR(String[] commonNames, KeyPair pair)
        throws OperatorCreationException, IOException {
    X500NameBuilder namebuilder = new X500NameBuilder(X500Name.getDefaultStyle());
    namebuilder.addRDN(BCStyle.CN, commonNames[0]);

    List<GeneralName> subjectAltNames = new ArrayList<>(commonNames.length);
    for (String cn : commonNames)
        subjectAltNames.add(new GeneralName(GeneralName.dNSName, cn));
    GeneralNames subjectAltName = new GeneralNames(subjectAltNames.toArray(new GeneralName[0]));

    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName.toASN1Primitive());

    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(),
            pair.getPublic());//from  w w  w . j av  a  2s.c  o  m
    p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
    ContentSigner signer = csBuilder.build(pair.getPrivate());
    PKCS10CertificationRequest request = p10Builder.build(signer);
    return request;
}

From source file:net.maritimecloud.pki.CertificateBuilder.java

License:Apache License

/**
 * Builds and signs a certificate. The certificate will be build on the given subject-public-key and signed with
 * the given issuer-private-key. The issuer and subject will be identified in the strings provided.
 *
 * @param serialNumber The serialnumber of the new certificate.
 * @param signerPrivateKey Private key for signing the certificate
 * @param signerPublicKey Public key of the signing certificate
 * @param subjectPublicKey Public key for the new certificate
 * @param issuer DN of the signing certificate
 * @param subject DN of the new certificate
 * @param customAttrs The custom MC attributes to include in the certificate
 * @param type Type of certificate, can be "ROOT", "INTERMEDIATE" or "ENTITY".
 * @param ocspUrl OCSP endpoint//from ww w .j  av a 2s.co m
 * @param crlUrl CRL endpoint - can be null
 * @return A signed X509Certificate
 * @throws Exception Throws exception on certificate generation errors.
 */
public X509Certificate buildAndSignCert(BigInteger serialNumber, PrivateKey signerPrivateKey,
        PublicKey signerPublicKey, PublicKey subjectPublicKey, X500Name issuer, X500Name subject,
        Map<String, String> customAttrs, String type, String ocspUrl, String crlUrl) throws Exception {
    // Dates are converted to GMT/UTC inside the cert builder
    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    Date expire = new GregorianCalendar(CERT_EXPIRE_YEAR, 0, 1).getTime();
    X509v3CertificateBuilder certV3Bldr = new JcaX509v3CertificateBuilder(issuer, serialNumber, now, // Valid from now...
            expire, // until CERT_EXPIRE_YEAR
            subject, subjectPublicKey);
    JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
    // Create certificate extensions
    if ("ROOTCA".equals(type)) {
        certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, true,
                        new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation
                                | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign
                                | X509KeyUsage.cRLSign));
    } else if ("INTERMEDIATE".equals(type)) {
        certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, true,
                        new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation
                                | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign
                                | X509KeyUsage.cRLSign));
    } else {
        // Subject Alternative Name
        GeneralName[] genNames = null;
        if (customAttrs != null && !customAttrs.isEmpty()) {
            genNames = new GeneralName[customAttrs.size()];
            Iterator<Map.Entry<String, String>> it = customAttrs.entrySet().iterator();
            int idx = 0;
            while (it.hasNext()) {
                Map.Entry<String, String> pair = it.next();
                if (PKIConstants.X509_SAN_DNSNAME.equals(pair.getKey())) {
                    genNames[idx] = new GeneralName(GeneralName.dNSName, pair.getValue());
                } else {
                    //genNames[idx] = new GeneralName(GeneralName.otherName, new DERUTF8String(pair.getKey() + ";" + pair.getValue()));
                    DERSequence othernameSequence = new DERSequence(
                            new ASN1Encodable[] { new ASN1ObjectIdentifier(pair.getKey()),
                                    new DERTaggedObject(true, 0, new DERUTF8String(pair.getValue())) });
                    genNames[idx] = new GeneralName(GeneralName.otherName, othernameSequence);
                }
                idx++;
            }
        }
        if (genNames != null) {
            certV3Bldr = certV3Bldr.addExtension(Extension.subjectAlternativeName, false,
                    new GeneralNames(genNames));
        }
    }
    // Basic extension setup
    certV3Bldr = certV3Bldr
            .addExtension(Extension.authorityKeyIdentifier, false,
                    extensionUtil.createAuthorityKeyIdentifier(signerPublicKey))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extensionUtil.createSubjectKeyIdentifier(subjectPublicKey));
    // CRL Distribution Points
    DistributionPointName distPointOne = new DistributionPointName(
            new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, crlUrl)));
    DistributionPoint[] distPoints = new DistributionPoint[1];
    distPoints[0] = new DistributionPoint(distPointOne, null, null);
    certV3Bldr.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints));
    // OCSP endpoint - is not available for the CAs
    if (ocspUrl != null) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUrl);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certV3Bldr.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }
    // Create the key signer
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNER_ALGORITHM);
    builder.setProvider(BC_PROVIDER_NAME);
    ContentSigner signer = builder.build(signerPrivateKey);
    return new JcaX509CertificateConverter().setProvider(BC_PROVIDER_NAME)
            .getCertificate(certV3Bldr.build(signer));
}

From source file:net.sf.keystore_explorer.crypto.x509.GeneralNameUtil.java

License:Open Source License

/**
 * Get string representation for General names that cannot cause a
 * IOException to be thrown. Unsupported are ediPartyName, otherName and
 * x400Address. Returns a blank string for these.
 *
 * @param generalName/*from w ww . j  a v  a 2s  . c  o m*/
 *            General name
 * @param addLinkForURI
 *            If true, convert URI to a clickable link
 * @return String representation of general name
 */
public static String safeToString(GeneralName generalName, boolean addLinkForURI) {

    if (generalName == null) {
        return "";
    }

    switch (generalName.getTagNo()) {
    case GeneralName.directoryName: {
        X500Name directoryName = (X500Name) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.DirectoryGeneralName"),
                directoryName.toString());
    }
    case GeneralName.dNSName: {
        DERIA5String dnsName = (DERIA5String) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.DnsGeneralName"), dnsName.getString());
    }
    case GeneralName.iPAddress: {
        byte[] ipAddressBytes = ((ASN1OctetString) generalName.getName()).getOctets();

        String ipAddressString = "";
        try {
            ipAddressString = InetAddress.getByAddress(ipAddressBytes).getHostAddress();
        } catch (UnknownHostException e) {
            // ignore -> results in empty IP address string
        }

        return MessageFormat.format(res.getString("GeneralNameUtil.IpAddressGeneralName"), ipAddressString);
    }
    case GeneralName.registeredID: {
        ASN1ObjectIdentifier registeredId = (ASN1ObjectIdentifier) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.RegisteredIdGeneralName"),
                ObjectIdUtil.toString(registeredId));
    }
    case GeneralName.rfc822Name: {
        DERIA5String rfc822Name = (DERIA5String) generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.Rfc822GeneralName"), rfc822Name.getString());
    }
    case GeneralName.uniformResourceIdentifier: {
        DERIA5String uri = (DERIA5String) generalName.getName();

        String link = addLinkForURI
                ? "<html><a href=\"" + uri.getString() + "\">" + uri.getString() + "</a></html>"
                : uri.getString();

        return MessageFormat.format(res.getString("GeneralNameUtil.UriGeneralName"), link);
    }
    case GeneralName.otherName: {
        // we currently only support UPN in otherName
        String upn = parseUPN(generalName);
        return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), "UPN", upn);
    }
    default: {
        return "";
    }
    }
}

From source file:net.sf.keystore_explorer.gui.crypto.generalname.DGeneralNameChooser.java

License:Open Source License

private void populate(GeneralName generalName) {
    if (generalName == null) {
        jrbDirectoryName.setSelected(true);
    } else {/*from   w w w. j a  v  a  2s .c  o m*/
        switch (generalName.getTagNo()) {
        case GeneralName.directoryName: {
            jrbDirectoryName.setSelected(true);
            jdnDirectoryName.setDistinguishedName((X500Name) generalName.getName());
            break;
        }
        case GeneralName.dNSName: {
            jrbDnsName.setSelected(true);
            jtfDnsName.setText(((DERIA5String) generalName.getName()).getString());
            break;
        }
        case GeneralName.iPAddress: {
            jrbIpAddress.setSelected(true);
            byte[] ipAddressBytes = ((ASN1OctetString) generalName.getName()).getOctets();
            try {
                jtfIpAddress.setText(InetAddress.getByAddress(ipAddressBytes).getHostAddress());
            } catch (UnknownHostException e) {
                // cannot happen here because user input was checked for validity
            }
            break;
        }
        case GeneralName.registeredID: {
            jrbRegisteredId.setSelected(true);
            joiRegisteredId.setObjectId((ASN1ObjectIdentifier) generalName.getName());
            break;
        }
        case GeneralName.rfc822Name: {
            jrbRfc822Name.setSelected(true);
            jtfRfc822Name.setText(((DERIA5String) generalName.getName()).getString());
            break;
        }
        case GeneralName.uniformResourceIdentifier: {
            jrbUniformResourceIdentifier.setSelected(true);
            jtfUniformResourceIdentifier.setText(((DERIA5String) generalName.getName()).getString());
            break;
        }
        case GeneralName.otherName: {
            jrbPrincipalName.setSelected(true);
            // we currently only support UPN in otherName
            jtfPrincipalName.setText(GeneralNameUtil.parseUPN(generalName));
            break;
        }
        }
    }
}

From source file:net.sf.keystore_explorer.gui.crypto.generalname.DGeneralNameChooser.java

License:Open Source License

private void okPressed() {
    try {//w  w w.  j av a2s.co m
        GeneralName newGeneralName = null;

        if (jrbDirectoryName.isSelected()) {
            X500Name directoryName = jdnDirectoryName.getDistinguishedName();

            if (directoryName == null) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.DirectoryNameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.directoryName, directoryName);
        } else if (jrbDnsName.isSelected()) {
            String dnsName = jtfDnsName.getText().trim();

            if (dnsName.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.DnsNameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.dNSName, new DERIA5String(dnsName));
        } else if (jrbIpAddress.isSelected()) {

            String ipAddress = jtfIpAddress.getText().trim();

            if (ipAddress.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.IpAddressValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (!IPAddress.isValid(ipAddress)) {
                JOptionPane.showMessageDialog(this, res.getString("DGeneralNameChooser.NotAValidIP.message"),
                        getTitle(), JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.iPAddress, ipAddress);
        } else if (jrbRegisteredId.isSelected()) {
            ASN1ObjectIdentifier registeredId = joiRegisteredId.getObjectId();

            if (registeredId == null) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.RegisteredIdValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.registeredID, registeredId);
        } else if (jrbRfc822Name.isSelected()) {
            String rfc822Name = jtfRfc822Name.getText().trim();

            if (rfc822Name.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.Rfc822NameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.rfc822Name, new DERIA5String(rfc822Name));
        } else if (jrbUniformResourceIdentifier.isSelected()) {
            String uniformResourceIdentifier = jtfUniformResourceIdentifier.getText().trim();

            if (uniformResourceIdentifier.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.UniformResourceIdentifierValueReq.message"),
                        getTitle(), JOptionPane.WARNING_MESSAGE);
                return;
            }

            newGeneralName = new GeneralName(GeneralName.uniformResourceIdentifier,
                    new DERIA5String(uniformResourceIdentifier));
        } else if (jrbPrincipalName.isSelected()) {
            String upnString = jtfPrincipalName.getText().trim();

            if (upnString.length() == 0) {
                JOptionPane.showMessageDialog(this,
                        res.getString("DGeneralNameChooser.PrincipalNameValueReq.message"), getTitle(),
                        JOptionPane.WARNING_MESSAGE);
                return;
            }

            ASN1EncodableVector asn1Vector = new ASN1EncodableVector();
            asn1Vector.add(new ASN1ObjectIdentifier(GeneralNameUtil.UPN_OID));
            asn1Vector.add(new DERTaggedObject(true, 0, new DERUTF8String(upnString)));

            newGeneralName = new GeneralName(GeneralName.otherName, new DERSequence(asn1Vector));
        }

        generalName = newGeneralName;
    } catch (Exception ex) {
        DError dError = new DError(this, ex);
        dError.setLocationRelativeTo(this);
        dError.setVisible(true);
        return;
    }

    closeDialog();
}

From source file:net.sf.portecle.crypto.X509Ext.java

License:Open Source License

/**
 * Get the supplied general name as a string ([general name type]=[general name]).
 * /*w  ww . ja va2 s. co m*/
 * <pre>
 * GeneralName ::= CHOICE {
 *     otherName                       [0]     OtherName,
 *     rfc822Name                      [1]     IA5String, x
 *     dNSName                         [2]     IA5String, x
 *     x400Address                     [3]     ORAddress,
 *     directoryName                   [4]     Name, x
 *     ediPartyName                    [5]     EDIPartyName,
 *     uniformResourceIdentifier       [6]     IA5String, x
 *     iPAddress                       [7]     OCTET STRING, x
 *     registeredID                    [8]     OBJECT IDENTIFIER x }
 * OtherName ::= SEQUENCE {
 *     type-id    OBJECT IDENTIFIER,
 *     value      [0] EXPLICIT ANY DEFINED BY type-id }
 * EDIPartyName ::= SEQUENCE {
 *     nameAssigner            [0]     DirectoryString OPTIONAL,
 *     partyName               [1]     DirectoryString }
 * DirectoryString ::= CHOICE {
 *     teletexString           TeletexString (SIZE (1..maxSize),
 *     printableString         PrintableString (SIZE (1..maxSize)),
 *     universalString         UniversalString (SIZE (1..maxSize)),
 *     utf8String              UTF8String (SIZE (1.. MAX)),
 *     bmpString               BMPString (SIZE(1..maxSIZE)) }
 * </pre>
 * 
 * @param generalName The general name
 * @return General name string
 * @throws IOException
 */
private String getGeneralNameString(GeneralName generalName, LinkClass linkClass) throws IOException {
    StringBuilder strBuff = new StringBuilder();
    int tagNo = generalName.getTagNo();

    switch (tagNo) {
    case GeneralName.otherName:
        ASN1Sequence other = (ASN1Sequence) generalName.getName();
        String sOid = ((ASN1ObjectIdentifier) other.getObjectAt(0)).getId();
        String sVal = stringify(other.getObjectAt(1));
        try {
            strBuff.append(RB.getString(sOid));
        } catch (MissingResourceException e) {
            strBuff.append(MessageFormat.format(RB.getString("GeneralName." + tagNo), sOid));
        }
        strBuff.append(": ");
        strBuff.append(sVal);
        break;

    case GeneralName.rfc822Name:
        String sRfc822 = generalName.getName().toString();
        String urlEnc = URLEncoder.encode(sRfc822, "UTF-8");
        strBuff.append(RB.getString("GeneralName." + tagNo));
        strBuff.append(": ");
        strBuff.append(getLink("mailto:" + urlEnc, escapeHtml(sRfc822), null));
        break;

    case GeneralName.dNSName:
    case GeneralName.registeredID:
    case GeneralName.x400Address: // TODO: verify formatting
    case GeneralName.ediPartyName: // TODO: verify formatting
        strBuff.append(RB.getString("GeneralName." + tagNo));
        strBuff.append(": ");
        strBuff.append(escapeHtml(generalName.getName()));
        break;

    case GeneralName.directoryName:
        ASN1Encodable name = generalName.getName();
        strBuff.append(RB.getString("GeneralName." + tagNo));
        strBuff.append(": ");
        // TODO: make E=foo@bar.com mail links
        strBuff.append(escapeHtml(name));
        break;

    case GeneralName.uniformResourceIdentifier:
        String sUri = generalName.getName().toString();
        strBuff.append(RB.getString("GeneralName." + tagNo));
        strBuff.append(": ");
        strBuff.append(getLink(sUri, escapeHtml(sUri), linkClass));
        break;

    case GeneralName.iPAddress:
        ASN1OctetString ipAddress = (ASN1OctetString) generalName.getName();

        byte[] bIpAddress = ipAddress.getOctets();

        // Output the IP Address components one at a time separated by dots
        StringBuilder sbIpAddress = new StringBuilder();

        for (int iCnt = 0, bl = bIpAddress.length; iCnt < bl; iCnt++) {
            // Convert from (possibly negative) byte to positive int
            sbIpAddress.append(bIpAddress[iCnt] & 0xFF);
            if ((iCnt + 1) < bIpAddress.length) {
                sbIpAddress.append('.');
            }
        }

        strBuff.append(RB.getString("GeneralName." + tagNo));
        strBuff.append(": ");
        strBuff.append(escapeHtml(sbIpAddress));
        break;

    default: // Unsupported general name type
        strBuff.append(
                MessageFormat.format(RB.getString("UnrecognizedGeneralNameType"), generalName.getTagNo()));
        strBuff.append(": ");
        strBuff.append(escapeHtml(generalName.getName()));
        break;
    }

    return strBuff.toString();
}

From source file:okhttp3.tls.HeldCertificateTest.java

License:Apache License

@Test
public void subjectAlternativeNames() throws CertificateParsingException {
    HeldCertificate heldCertificate = new HeldCertificate.Builder().addSubjectAlternativeName("1.1.1.1")
            .addSubjectAlternativeName("cash.app").build();

    X509Certificate certificate = heldCertificate.certificate();
    List<List<?>> subjectAlternativeNames = new ArrayList<>(certificate.getSubjectAlternativeNames());
    assertEquals(subjectAlternativeNames, Arrays.asList(Arrays.asList(GeneralName.iPAddress, "1.1.1.1"),
            Arrays.asList(GeneralName.dNSName, "cash.app")));
}

From source file:org.apache.cloudstack.utils.security.CertUtils.java

License:Apache License

public static X509Certificate generateV3Certificate(final X509Certificate caCert, final KeyPair caKeyPair,
        final PublicKey clientPublicKey, final String subject, final String signatureAlgorithm,
        final int validityDays, final List<String> dnsNames, final List<String> publicIPAddresses)
        throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException,
        InvalidKeyException, SignatureException, OperatorCreationException {

    final DateTime now = DateTime.now(DateTimeZone.UTC);
    final BigInteger serial = generateRandomBigInt();
    final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    final X509v3CertificateBuilder certBuilder;
    if (caCert == null) {
        // Generate CA certificate
        certBuilder = new JcaX509v3CertificateBuilder(new X500Name(subject), serial,
                now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Name(subject),
                clientPublicKey);//from ww w.j  a v a  2 s .  c  om

        certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));
    } else {
        // Generate client certificate
        certBuilder = new JcaX509v3CertificateBuilder(caCert, serial, now.minusHours(12).toDate(),
                now.plusDays(validityDays).toDate(), new X500Principal(subject), clientPublicKey);

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(caCert));
    }

    certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
            extUtils.createSubjectKeyIdentifier(clientPublicKey));

    final List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
    if (publicIPAddresses != null) {
        for (final String publicIPAddress : publicIPAddresses) {
            if (Strings.isNullOrEmpty(publicIPAddress)) {
                continue;
            }
            subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, publicIPAddress));
        }
    }
    if (dnsNames != null) {
        for (final String dnsName : dnsNames) {
            if (Strings.isNullOrEmpty(dnsName)) {
                continue;
            }
            subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, dnsName));
        }
    }
    if (subjectAlternativeNames.size() > 0) {
        final GeneralNames subjectAltNames = GeneralNames
                .getInstance(new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[] {})));
        certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    }

    final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC")
            .build(caKeyPair.getPrivate());
    final X509CertificateHolder certHolder = certBuilder.build(signer);
    final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
    if (caCert != null) {
        cert.verify(caCert.getPublicKey());
    } else {
        cert.verify(caKeyPair.getPublic());
    }
    return cert;
}