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

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

Introduction

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

Prototype

int directoryName

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

Click Source Link

Usage

From source file:org.cesecore.certificates.certificate.certextensions.standard.NameConstraint.java

License:Open Source License

/**
 * Returns the GeneralName data (as a byte array or String) from an encoded string.
 *///from  w  ww  . java 2 s.  c o  m
private static Object getNameConstraintData(String encoded) {
    int type = getNameConstraintType(encoded);
    String data = encoded.split(":", 2)[1];

    switch (type) {
    case GeneralName.dNSName:
    case GeneralName.directoryName:
    case GeneralName.rfc822Name:
        return data;
    case GeneralName.iPAddress:
        try {
            return Hex.decodeHex(data.toCharArray());
        } catch (DecoderException e) {
            throw new IllegalStateException("internal name constraint data could not be decoded as hex", e);
        }
    default:
        throw new UnsupportedOperationException("Unsupported name constraint type " + type);
    }
}

From source file:org.cesecore.certificates.certificate.certextensions.standard.NameConstraint.java

License:Open Source License

/**
 * Formats an encoded name constraint from parseNameConstraintEntry into human-readable form.
 */// w w  w .  j  a  v a2 s .c om
private static String formatNameConstraintEntry(String encoded) {
    if (encoded == null) {
        return "";
    }

    int type = getNameConstraintType(encoded);
    Object data = getNameConstraintData(encoded);

    switch (type) {
    case GeneralName.dNSName:
    case GeneralName.directoryName:
        return (String) data; // not changed during encoding
    case GeneralName.iPAddress:
        byte[] bytes = (byte[]) data;
        byte[] ip = new byte[bytes.length / 2];
        byte[] netmaskBytes = new byte[bytes.length / 2];
        System.arraycopy(bytes, 0, ip, 0, ip.length);
        System.arraycopy(bytes, ip.length, netmaskBytes, 0, netmaskBytes.length);

        int netmask = 0;
        for (int i = 0; i < 8 * netmaskBytes.length; i++) {
            final boolean one = (netmaskBytes[i / 8] >> (7 - i % 8) & 1) == 1;
            if (one && netmask == i) {
                netmask++; // leading ones
            } else if (one) {
                // trailings ones = error!
                throw new IllegalArgumentException("Unsupported netmask with mixed ones/zeros");
            }
        }

        try {
            return InetAddress.getByAddress(ip).getHostAddress() + "/" + netmask;
        } catch (UnknownHostException e) {
            throw new IllegalArgumentException(e);
        }
    case GeneralName.rfc822Name:
        // Prepend @ is it's only the domain part to distinguish from DNS names
        String str = (String) data;
        return (str.contains("@") ? str : "@" + str);
    default:
        throw new UnsupportedOperationException("Unsupported name constraint type " + type);
    }
}

From source file:org.cryptacular.x509.ExtensionReaderTest.java

License:Open Source License

private GeneralName dirName(final String dn) {
    return new GeneralName(GeneralName.directoryName, dn);
}

From source file:org.jruby.ext.openssl.X509Extension.java

License:LGPL

@SuppressWarnings("unchecked")
private static boolean formatGeneralName(final GeneralName name, final ByteList out, final boolean slashed) {
    final ASN1Encodable obj = name.getName();
    String val;
    boolean tagged = false;
    switch (name.getTagNo()) {
    case GeneralName.rfc822Name:
        if (!tagged)
            out.append('e').append('m').append('a').append('i').append('l').append(':');
        tagged = true;//  w w  w . j a  v  a2s  .  c  om
    case GeneralName.dNSName:
        if (!tagged)
            out.append('D').append('N').append('S').append(':');
        tagged = true;
    case GeneralName.uniformResourceIdentifier:
        if (!tagged)
            out.append('U').append('R').append('I').append(':');
        val = DERIA5String.getInstance(obj).getString();
        out.append(ByteList.plain(val));
        break;
    case GeneralName.directoryName:
        out.append('D').append('i').append('r').append('N').append('a').append('m').append('e').append(':');
        final X500Name dirName = X500Name.getInstance(obj);
        if (slashed) {
            final RDN[] rdns = dirName.getRDNs();
            final Hashtable defaultSymbols = getDefaultSymbols();
            for (int i = 0; i < rdns.length; i++) {
                appendRDN(out.append('/'), rdns[i], defaultSymbols);
            }
        } else {
            out.append(ByteList.plain(dirName.toString()));
        }
        break;
    case GeneralName.iPAddress:
        out.append('I').append('P').append(':');
        final byte[] ip = ((ASN1OctetString) name.getName()).getOctets();
        int len = ip.length;
        boolean ip4 = len == 4;
        for (int i = 0; i < ip.length; i++) {
            out.append(ConvertBytes.intToCharBytes(((int) ip[i]) & 0xff));
            if (i != len - 1) {
                if (ip4)
                    out.append('.');
                else
                    out.append(':').append(':');
            }
        }
        break;
    case GeneralName.otherName:
        out.append('o').append('t').append('h').append('e').append('r').append('N').append('a').append('m')
                .append('e').append(':');
        out.append(ByteList.plain(obj.toString()));
        return true;
    //tagged = true;
    case GeneralName.registeredID:
        out.append('R').append('I').append('D').append(':');
        //tagged = true;
    default:
        out.append(ByteList.plain(obj.toString()));
    }
    return false;
}

From source file:org.jruby.ext.openssl.X509ExtensionFactory.java

License:LGPL

private static ASN1Encodable parseSubjectAltName(final String valuex) throws IOException {
    if (valuex.startsWith(DNS_)) {
        final String dns = valuex.substring(DNS_.length());
        return new GeneralName(GeneralName.dNSName, dns);
    }// ww w.j ava  2 s.c  o m
    if (valuex.startsWith(DNS_Name_)) {
        final String dns = valuex.substring(DNS_Name_.length());
        return new GeneralName(GeneralName.dNSName, dns);
    }
    if (valuex.startsWith(URI_)) {
        final String uri = valuex.substring(URI_.length());
        return new GeneralName(GeneralName.uniformResourceIdentifier, uri);
    }
    if (valuex.startsWith(RID_)) {
        final String rid = valuex.substring(RID_.length());
        return new GeneralName(GeneralName.registeredID, rid);
    }
    if (valuex.startsWith(email_)) {
        final String mail = valuex.substring(email_.length());
        return new GeneralName(GeneralName.rfc822Name, mail);
    }
    if (valuex.startsWith("IP:") || valuex.startsWith("IP Address:")) {
        final int idx = valuex.charAt(2) == ':' ? 3 : 11;
        String[] vals = valuex.substring(idx).split("\\.|::");
        final byte[] ip = new byte[vals.length];
        for (int i = 0; i < vals.length; i++) {
            ip[i] = (byte) (Integer.parseInt(vals[i]) & 0xff);
        }
        return new GeneralName(GeneralName.iPAddress, new DEROctetString(ip));
    }
    if (valuex.startsWith("other")) { // otherName || othername
        final String other = valuex.substring(otherName_.length());
        return new GeneralName(GeneralName.otherName, other);
    }
    if (valuex.startsWith("dir")) { // dirName || dirname
        final String dir = valuex.substring(dirName_.length());
        return new GeneralName(GeneralName.directoryName, dir);
    }

    throw new IOException("could not parse SubjectAltName: " + valuex);

}

From source file:org.jruby.ext.openssl.x509store.X509Utils.java

License:LGPL

/**
 * c: X509_check_issued/*  www.j ava2  s  .c om*/
 */
public static int checkIfIssuedBy(X509AuxCertificate issuer, X509AuxCertificate subject) throws Exception {
    if (!issuer.getSubjectX500Principal().equals(subject.getIssuerX500Principal())) {
        return V_ERR_SUBJECT_ISSUER_MISMATCH;
    }

    if (subject.getExtensionValue("2.5.29.35") != null) { //authorityKeyID
        // I hate ASN1 and DER
        Object key = get(subject.getExtensionValue("2.5.29.35"));
        if (!(key instanceof ASN1Sequence)) {
            key = get(key);
        }

        ASN1Sequence seq = (ASN1Sequence) key;
        AuthorityKeyIdentifier sakid = null;
        if (seq.size() == 1 && (seq.getObjectAt(0) instanceof ASN1OctetString)) {
            sakid = AuthorityKeyIdentifier
                    .getInstance(new DLSequence(new DERTaggedObject(0, seq.getObjectAt(0))));
        } else {
            sakid = AuthorityKeyIdentifier.getInstance(seq);
        }

        if (sakid.getKeyIdentifier() != null) {
            if (issuer.getExtensionValue("2.5.29.14") != null) {
                DEROctetString der = (DEROctetString) get(issuer.getExtensionValue("2.5.29.14"));
                if (der.getOctets().length > 20) {
                    der = (DEROctetString) get(der.getOctets());
                }
                SubjectKeyIdentifier iskid = SubjectKeyIdentifier.getInstance(der);
                if (iskid.getKeyIdentifier() != null) {
                    if (!Arrays.equals(sakid.getKeyIdentifier(), iskid.getKeyIdentifier())) {
                        return V_ERR_AKID_SKID_MISMATCH;
                    }
                }
            }
        }
        if (sakid.getAuthorityCertSerialNumber() != null
                && !sakid.getAuthorityCertSerialNumber().equals(issuer.getSerialNumber())) {
            return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
        }
        if (sakid.getAuthorityCertIssuer() != null) {
            GeneralName[] gens = sakid.getAuthorityCertIssuer().getNames();
            X500Name nm = null;
            for (int i = 0; i < gens.length; i++) {
                if (gens[i].getTagNo() == GeneralName.directoryName) {
                    ASN1Encodable nameTmp = gens[i].getName();
                    if (nameTmp instanceof X500Name) {
                        nm = (X500Name) nameTmp;
                    } else if (nameTmp instanceof ASN1Sequence) {
                        nm = X500Name.getInstance((ASN1Sequence) nameTmp);
                    } else {
                        throw new RuntimeException("unknown name type in X509Utils: " + nameTmp);
                    }
                    break;
                }
            }
            if (nm != null) {
                if (!(new Name(nm).isEqual(issuer.getIssuerX500Principal()))) {
                    return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
                }
            }
        }
    }

    if (subject.getExtensionValue("1.3.6.1.5.5.7.1.14") != null) {
        if (issuer.getKeyUsage() != null && !issuer.getKeyUsage()[0]) { // KU_DIGITAL_SIGNATURE
            return V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
        }
    } else if (issuer.getKeyUsage() != null && !issuer.getKeyUsage()[5]) { // KU_KEY_CERT_SIGN
        return V_ERR_KEYUSAGE_NO_CERTSIGN;
    }
    return V_OK;
}

From source file:org.kse.gui.dialogs.extensions.DAuthorityKeyIdentifier.java

License:Open Source License

private void prepopulateWithAuthorityCertDetails(X500Name authorityCertName,
        BigInteger authorityCertSerialNumber) {
    if (authorityCertName != null) {
        try {//from   w  w w  .  j  a v a2 s. c  om
            GeneralName generalName = new GeneralName(GeneralName.directoryName, authorityCertName);
            GeneralNames generalNames = new GeneralNames(generalName);

            jgnAuthorityCertIssuer.setGeneralNames(generalNames);
        } catch (Exception ex) {
            DError dError = new DError(this, ex);
            dError.setLocationRelativeTo(this);
            dError.setVisible(true);
            return;
        }
    }

    if (authorityCertSerialNumber != null) {
        jtfAuthorityCertSerialNumber.setText("" + authorityCertSerialNumber.toString());
        jtfAuthorityCertSerialNumber.setCaretPosition(0);
    }
}

From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java

License:Apache License

protected List<ASN1Encodable> extractAlternativeNames(String prefix) {
    List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
    for (Object key : componentProperties.keySet()) {
        final String attributeKey = String.valueOf(key);
        if (attributeKey.startsWith(prefix)) {
            String nameTypeString = attributeKey.substring(attributeKey.lastIndexOf(".") + 1);
            String nameValue = getProperty(attributeKey);
            int nameType = 0;
            switch (nameTypeString) {
            case NAME_DNS:
                nameType = GeneralName.dNSName;
                break;
            case NAME_DIRECTORY:
                nameType = GeneralName.directoryName;
                break;
            case NAME_IP:
                nameType = GeneralName.iPAddress;
                break;
            case NAME_OTHER:
                nameType = GeneralName.otherName;
                break;
            default:
                throw new IllegalArgumentException(
                        String.format("Alternative name '%s' not supported.", nameTypeString));
            }/*from   w w w.j a  v a  2  s.com*/

            if (StringUtils.isNotBlank(nameValue)) {
                subjectAlternativeNames.add(new GeneralName(nameType, nameValue));
            }
        }
    }

    return subjectAlternativeNames;
}

From source file:org.qipki.crypto.x509.X509ExtensionsReaderImpl.java

License:Open Source License

@Override
public Map.Entry<X509GeneralName, String> asImmutableMapEntry(GeneralName generalName) {
    int nameType = generalName.getTagNo();
    X509GeneralName x509GeneralName = null;
    String value = null;/* w w  w.j a  v  a  2s  . c o  m*/
    switch (nameType) {
    case GeneralName.otherName:
        ASN1Sequence otherName = (ASN1Sequence) generalName.getName();
        // String oid = ( ( DERObjectIdentifier ) otherName.getObjectAt( 0 ) ).getId();
        x509GeneralName = X509GeneralName.otherName;
        value = cryptCodex.toString(otherName.getObjectAt(1));
        break;
    case GeneralName.rfc822Name:
        x509GeneralName = X509GeneralName.rfc822Name;
        value = generalName.getName().toString();
        break;
    case GeneralName.dNSName:
        x509GeneralName = X509GeneralName.dNSName;
        value = generalName.getName().toString();
        break;
    case GeneralName.registeredID:
        x509GeneralName = X509GeneralName.registeredID;
        value = generalName.getName().toString();
        break;
    case GeneralName.x400Address:
        x509GeneralName = X509GeneralName.x400Address;
        value = generalName.getName().toString();
        break;
    case GeneralName.ediPartyName:
        x509GeneralName = X509GeneralName.ediPartyName;
        value = generalName.getName().toString();
        break;
    case GeneralName.directoryName:
        x509GeneralName = X509GeneralName.directoryName;
        value = new X500Principal(((X509Name) generalName.getName()).toString())
                .getName(X500Principal.CANONICAL);
        break;
    case GeneralName.uniformResourceIdentifier:
        x509GeneralName = X509GeneralName.uniformResourceIdentifier;
        value = generalName.getName().toString();
        break;
    case GeneralName.iPAddress: // What about IPv6 addresses ?
        ASN1OctetString iPAddress = (ASN1OctetString) generalName.getName();
        byte[] iPAddressBytes = iPAddress.getOctets();
        StringBuilder sb = new StringBuilder();
        for (int idx = 0; idx < iPAddressBytes.length; idx++) {
            sb.append(iPAddressBytes[idx] & 0xFF);
            if (idx + 1 < iPAddressBytes.length) {
                sb.append(".");
            }
        }
        x509GeneralName = X509GeneralName.iPAddress;
        value = sb.toString();
        break;
    default:
        x509GeneralName = X509GeneralName.unknownGeneralName;
        value = generalName.getName().toString();
    }
    return new ImmutableMapEntry(x509GeneralName, value);
}

From source file:org.tdmx.client.crypto.certificate.CredentialUtils.java

License:Open Source License

/**
 * Create the credentials of a ZoneAdministrator.
 * /* w  ww .  j  ava2  s  .  com*/
 * The ZoneAdministrator credentials are long validity.
 * 
 * @param req
 * @return
 * @throws CryptoCertificateException
 */
public static PKIXCredential createZoneAdministratorCredential(ZoneAdministrationCredentialSpecifier req)
        throws CryptoCertificateException {
    KeyPair kp = null;
    try {
        kp = req.getKeyAlgorithm().generateNewKeyPair();
    } catch (CryptoException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_KEYPAIR_GENERATION, e);
    }

    PublicKey publicKey = kp.getPublic();
    PrivateKey privateKey = kp.getPrivate();

    X500NameBuilder subjectBuilder = new X500NameBuilder();
    if (StringUtils.hasText(req.getCountry())) {
        subjectBuilder.addRDN(BCStyle.C, req.getCountry());
    }
    if (StringUtils.hasText(req.getLocation())) {
        subjectBuilder.addRDN(BCStyle.L, req.getLocation());
    }
    if (StringUtils.hasText(req.getOrg())) {
        subjectBuilder.addRDN(BCStyle.O, req.getOrg());
    }
    if (StringUtils.hasText(req.getOrgUnit())) {
        if (TDMX_DOMAIN_CA_OU.equals(req.getOrgUnit())) {
            throw new CryptoCertificateException(CertificateResultCode.ERROR_INVALID_OU);
        }
        subjectBuilder.addRDN(BCStyle.OU, req.getOrgUnit());
    }
    if (StringUtils.hasText(req.getEmailAddress())) {
        subjectBuilder.addRDN(BCStyle.E, req.getEmailAddress());
    }
    if (StringUtils.hasText(req.getTelephoneNumber())) {
        subjectBuilder.addRDN(BCStyle.TELEPHONE_NUMBER, req.getTelephoneNumber());
    }
    if (StringUtils.hasText(req.getCn())) {
        subjectBuilder.addRDN(BCStyle.CN, req.getCn());
    }
    X500Name subject = subjectBuilder.build();
    X500Name issuer = subject;
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, new BigInteger("1"),
            req.getNotBefore().getTime(), req.getNotAfter().getTime(), subject, publicKey);

    try {
        BasicConstraints cA = new BasicConstraints(1);
        certBuilder.addExtension(Extension.basicConstraints, true, cA);

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(publicKey));
        certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                extUtils.createSubjectKeyIdentifier(publicKey));

        KeyUsage ku = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign);
        certBuilder.addExtension(Extension.keyUsage, false, ku);

        // RFC5280 http://tools.ietf.org/html/rfc5280#section-4.2.1.10
        // The CA has a CN which is not part of the name constraint - but we can constrain
        // any domain certificate issued to be limited to some OU under the O.
        X500NameBuilder subjectConstraintBuilder = new X500NameBuilder();
        if (StringUtils.hasText(req.getCountry())) {
            subjectConstraintBuilder.addRDN(BCStyle.C, req.getCountry());
        }
        if (StringUtils.hasText(req.getLocation())) {
            subjectConstraintBuilder.addRDN(BCStyle.L, req.getLocation());
        }
        if (StringUtils.hasText(req.getOrg())) {
            subjectConstraintBuilder.addRDN(BCStyle.O, req.getOrg());
        }
        if (StringUtils.hasText(req.getOrgUnit())) {
            subjectConstraintBuilder.addRDN(BCStyle.OU, req.getOrgUnit());
        }
        subjectConstraintBuilder.addRDN(BCStyle.OU, TDMX_DOMAIN_CA_OU);
        X500Name nameConstraint = subjectConstraintBuilder.build();

        GeneralName snc = new GeneralName(GeneralName.directoryName, nameConstraint);
        GeneralSubtree snSubtree = new GeneralSubtree(snc, new BigInteger("0"), null);
        NameConstraints nc = new NameConstraints(new GeneralSubtree[] { snSubtree }, null);
        certBuilder.addExtension(Extension.nameConstraints, true, nc);

        certBuilder.addExtension(TdmxZoneInfo.tdmxZoneInfo, false, req.getZoneInfo());

        ContentSigner signer = SignatureAlgorithm.getContentSigner(privateKey, req.getSignatureAlgorithm());
        byte[] certBytes = certBuilder.build(signer).getEncoded();

        PKIXCertificate c = CertificateIOUtils.decodeX509(certBytes);

        return new PKIXCredential(c, privateKey);
    } catch (CertIOException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_CERT_GENERATION, e);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_CERT_GENERATION, e);
    } catch (IOException e) {
        throw new CryptoCertificateException(CertificateResultCode.ERROR_CA_CERT_GENERATION, e);
    }
}