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

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

Introduction

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

Prototype

int iPAddress

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

Click Source Link

Usage

From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyAddressRestrictionData.java

License:Open Source License

/**
 * Adds a new permitted IP addressSpace to the data structure.
 * //  w w  w. ja v  a2 s  .  c o m
 * @param address The address space to add to the allowed ip address
 *                space. Example of the format: 192.168.0.0/16. Which
 *                equals a 192.168.0.0 with a net mask 255.255.0.0. A
 *                single IP address can be defined as
 *                xxx.xxx.xxx.xxx/32. <br> It is also possible to provide IPv6 
 *                addresses.
 *                See <a href="http://www.ietf.org/rfc/rfc4632.txt"> RFC4632.</a>
 */
public void addPermittedIPAddressWithNetmask(String address) {
    permittedGeneralSubtrees
            .add(new GeneralSubtree(new GeneralName(GeneralName.iPAddress, address), null, null));
}

From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyAddressRestrictionData.java

License:Open Source License

/**
 * Adds a new excluded IP addressSpace to the data structure.
 * //from  w  w w. j  av  a2  s  . c om
 * @param address The address space to add to the allowed ip address
 *                space. Example of the format: 192.168.0.0/16. Which
 *                equals a 192.168.0.0 with a net mask 255.255.0.0. A
 *                single IP address can be defined as
 *                xxx.xxx.xxx.xxx/32. <br> It is also possible to provide IPv6 
 *                addresses. See <a href="http://www.ietf.org/rfc/rfc4632.txt"> RFC4632.</a> 
 */
public void addExcludedIPAddressWithNetmask(String address) {
    excludedGeneralSubtrees
            .add(new GeneralSubtree(new GeneralName(GeneralName.iPAddress, address), null, null));
}

From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyAddressRestrictionData.java

License:Open Source License

/**
 * Generates a string array of IP address spaces from a list of
 * GeneralSubtrees.//w w  w  . j  av a 2  s.c  o  m
 * 
 * @param subtrees The list of GeneralSubtrees to parse. Null as input
 *                will return null.
 * @return the array of IP address spaces.
 */
private static byte[][] subtreesIntoArray(List<GeneralSubtree> subtrees) {
    if (subtrees == null)
        return null;

    List<byte[]> ips = new ArrayList<byte[]>();
    Iterator<GeneralSubtree> enumGeneralNames = subtrees.iterator();
    while (enumGeneralNames.hasNext()) {
        GeneralName item = enumGeneralNames.next().getBase();
        if (item.getTagNo() == GeneralName.iPAddress) {
            ASN1OctetString octets = (ASN1OctetString) item.getName();
            byte[] bytes = octets.getOctets();
            ips.add(bytes);
        }
    }
    return ips.toArray(new byte[ips.size()][]);
}

From source file:fathom.x509.X509Utils.java

License:Apache License

/**
 * Creates a new SSL certificate signed by the CA private key and stored in
 * keyStore./*w w w  .  j a  v  a 2s .  c om*/
 *
 * @param sslMetadata
 * @param caPrivateKey
 * @param caCert
 * @param targetStoreFile
 * @param x509log
 */
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey,
        X509Certificate caCert, File targetStoreFile, X509Log x509log) {
    try {
        KeyPair pair = newKeyPair();

        X500Name webDN = buildDistinguishedName(sslMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN,
                BigInteger.valueOf(System.currentTimeMillis()), sslMetadata.notBefore, sslMetadata.notAfter,
                webDN, pair.getPublic());

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
                extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));

        // support alternateSubjectNames for SSL certificates
        List<GeneralName> altNames = new ArrayList<GeneralName>();
        if (isIpAddress(sslMetadata.commonName)) {
            altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
        }
        if (altNames.size() > 0) {
            GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }

        ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC)
                .build(caPrivateKey);
        X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
                .getCertificate(certBuilder.build(caSigner));

        cert.checkValidity(new Date());
        cert.verify(caCert.getPublicKey());

        // Save to keystore
        KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password);
        serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(),
                new Certificate[] { cert, caCert });
        saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);

        x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(),
                cert.getSubjectDN().getName()));

        // update serial number in metadata object
        sslMetadata.serialNumber = cert.getSerialNumber().toString();

        return cert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate SSL certificate!", t);
    }
}

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 {/* w w w.  j a  va 2  s. c om*/
            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.vertx.config.vault.utils.Certificates.java

License:Apache License

/**
 * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder
 *
 * @param keyPair The RSA keypair with which to generate the certificate
 * @param issuer  The issuer (and subject) to use for the certificate
 * @return An X509 certificate//from ww w .j a  va 2  s.  co m
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
private static X509Certificate generateCert(final KeyPair keyPair, final String issuer)
        throws IOException, OperatorCreationException, CertificateException, NoSuchProviderException,
        NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    final String subject = issuer;
    final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(new X500Name(issuer),
            BigInteger.ONE, new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(subject),
            SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
    certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false,
            subjectAltNames);

    final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
            .find("SHA1WithRSAEncryption");
    final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
    final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    final ContentSigner signer = signerBuilder.build(keyp);
    final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);

    final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder);
    certificate.checkValidity(new Date());
    certificate.verify(keyPair.getPublic());
    return certificate;
}

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  va 2s.  c om*/
 *            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 ww  w.j av  a 2s.com*/
        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  w  w 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();
}

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]).
 * /*from   w  ww .j  av  a 2  s  . com*/
 * <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();
}