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

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

Introduction

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

Prototype

int otherName

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

Click Source Link

Usage

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: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  .  ja v a 2s  .  c o 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:hu.akarnokd.utils.crypto.KeystoreManager.java

License:Apache License

/**
 * Generate a X509 certificate for the given keypair.
 * The distinguished names must be in format: CN=cName, OU=orgUnit, O=org, L=city, S=state, C=countryCode
 * use backslash to escape a comma/*  w ww  . ja v a  2  s.c om*/
 * @param keypair the keypair
 * @param months the validity length in months
 * @param issuerDN the issuer distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI"
 * @param subjectDN the subject distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI"
 * @param domain domain of the server to store in the subject alternative name extension
 * @param signAlgorithm the signing algorithm to use
 * @return the generated X509 certificate
 */
public X509Certificate createX509Certificate(KeyPair keypair, int months, String issuerDN, String subjectDN,
        String domain, String signAlgorithm) {
    try {
        // calendar for date calculations
        GregorianCalendar cal = new GregorianCalendar();

        // extract keypair components
        PublicKey pubKey = keypair.getPublic();
        PrivateKey privKey = keypair.getPrivate();

        // generate a random serial number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(System.currentTimeMillis());
        byte[] serialNo = new byte[8];
        random.nextBytes(serialNo);
        BigInteger serial = new BigInteger(serialNo).abs();

        // create the certificate generator
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.reset();

        // set certificate attributes
        certGen.setSerialNumber(serial);
        cal.setTimeInMillis(System.currentTimeMillis());
        certGen.setNotBefore(cal.getTime());
        cal.add(GregorianCalendar.MONTH, months);
        certGen.setNotAfter(cal.getTime());
        certGen.setPublicKey(pubKey);
        certGen.setSignatureAlgorithm(signAlgorithm);
        certGen.setIssuerDN(new X509Name(issuerDN));
        certGen.setSubjectDN(new X509Name(subjectDN));

        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));

        // create subject alternative name
        boolean isCritical = subjectDN == null || "".equals(subjectDN.trim());
        DERSequence othernameSeq = new DERSequence(
                new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"),
                        new DERTaggedObject(true, 0, new DERUTF8String(domain)) });
        GeneralName othernameGen = new GeneralName(GeneralName.otherName, othernameSeq);
        GeneralNames subjectAlternatives = new GeneralNames(othernameGen);
        certGen.addExtension(X509Extensions.SubjectAlternativeName, isCritical, subjectAlternatives);

        // finally generate the certificate
        X509Certificate cert = certGen.generateX509Certificate(privKey, BC_PROVIDER.getName(),
                new SecureRandom());
        cert.checkValidity(new Date());
        cert.verify(pubKey);

        return cert;
    } catch (NoSuchAlgorithmException ex) {
        throw new KeystoreFault(ex);
    } catch (CertificateException ex) {
        throw new KeystoreFault(ex);
    } catch (SignatureException ex) {
        throw new KeystoreFault(ex);
    } catch (NoSuchProviderException ex) {
        throw new KeystoreFault(ex);
    } catch (InvalidKeyException ex) {
        throw new KeystoreFault(ex);
    }
}

From source file:net.felsing.client_cert.utilities.CertificateFabric.java

License:Open Source License

private void getSubjectAlternativeNames(PKCS10CertificationRequest csr) {
    subjectAlternativeNames = new ArrayList<>(new ArrayList<>());
    // GeneralName.otherName is lowest and
    // GeneralName.registeredID is highest id
    for (int i = GeneralName.otherName; i <= GeneralName.registeredID; i++) {
        subjectAlternativeNames.add(new ArrayList<>());
    }/*ww  w.j  av  a2 s .c  o  m*/

    try {
        Attribute[] certAttributes = csr.getAttributes();
        for (Attribute attribute : certAttributes) {
            if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                // @ToDo: Is there really one object only?
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns != null) {
                    GeneralName[] names = gns.getNames();
                    for (GeneralName name : names) {
                        subjectAlternativeNames.get(name.getTagNo()).add(name.getName().toString());
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.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.
 *
 * @return A signed X509Certificate/*from   w ww .  java  2 s  . c  o m*/
 * @throws Exception
 */
public X509Certificate buildAndSignCert(BigInteger serialNumber, PrivateKey signerPrivateKey,
        PublicKey signerPublicKey, PublicKey subjectPublicKey, X500Name issuer, X500Name subject,
        Map<String, String> customAttrs, String type) 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();
                //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, CRL_URL)));
    DistributionPoint[] distPoints = new DistributionPoint[1];
    distPoints[0] = new DistributionPoint(distPointOne, null, null);
    certV3Bldr.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints));
    // OCSP endpoint
    GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, OCSP_URL);
    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.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 www . 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   ww  w.  ja  v  a  2s.  co 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.crypto.x509.GeneralNameUtil.java

License:Open Source License

/**
 * Get string representation for all General Names.
 *
 * @param generalName//from   w  w w . j a  v  a2s.co  m
 *            General name
 * @return String representation of general name
 * @throws IOException
 *             If general name is invalid
 */
public static String toString(GeneralName generalName) throws IOException {

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

    switch (generalName.getTagNo()) {
    case GeneralName.ediPartyName: {

        /* EDIPartyName ::= SEQUENCE {
         *      nameAssigner            [0]     DirectoryString OPTIONAL,
         *      partyName               [1]     DirectoryString }
         */
        ASN1Sequence ediPartyName = (ASN1Sequence) generalName.getName();

        DirectoryString nameAssigner = DirectoryString.getInstance(ediPartyName.getObjectAt(0));
        DirectoryString partyName = DirectoryString.getInstance(ediPartyName.getObjectAt(1));

        String nameAssignerStr = null;
        if (nameAssigner != null) { // Optional
            nameAssignerStr = nameAssigner.getString();
        }

        String partyNameStr = partyName.getString();
        if (nameAssignerStr != null) {
            return MessageFormat.format(res.getString("GeneralNameUtil.EdiPartyGeneralName"), nameAssignerStr,
                    partyNameStr);
        } else {
            return MessageFormat.format(res.getString("GeneralNameUtil.EdiPartyGeneralNameNoAssigner"),
                    partyNameStr);
        }
    }
    case GeneralName.otherName: {

        return parseUPN(generalName);
    }
    case GeneralName.x400Address: {
        /*
         * No support for this at the moment - just get a hex dump
         * The Oracle CertificateFactory blows up if a certificate extension contains this anyway
         */
        ASN1Encodable x400Address = generalName.getName();

        return MessageFormat.format(res.getString("GeneralNameUtil.X400AddressGeneralName"),
                HexUtil.getHexString(x400Address.toASN1Primitive().getEncoded(ASN1Encoding.DER)));
    }
    default: {
        return safeToString(generalName, true);
    }
    }
}

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. ja 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 {/*from ww w. j  ava 2 s. com*/
        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();
}