Search in sources :

Example 91 with GeneralName

use of org.spongycastle.asn1.x509.GeneralName in project XobotOS by xamarin.

the class X509CertSelector method addPathToName.

/**
     * Adds a {@literal "pathToName"} to the respective criterion.
     *
     * @param type
     *            the type of the name.
     * @param name
     *            the name in string format.
     * @throws IOException
     *             if parsing fails.
     * @see #setPathToNames
     */
public void addPathToName(int type, String name) throws IOException {
    GeneralName path_name = new GeneralName(type, name);
    // create only if there was not any errors
    if (pathToNames == null) {
        pathToNames = new ArrayList<GeneralName>();
    }
    pathToNames.add(path_name);
}
Also used : GeneralName(org.apache.harmony.security.x509.GeneralName)

Example 92 with GeneralName

use of org.spongycastle.asn1.x509.GeneralName in project XobotOS by xamarin.

the class X509CertSelector method toString.

/**
     * Returns a string representation of this {@code X509CertSelector}
     * instance.
     *
     * @return a string representation of this {@code X509CertSelector}
     *         instance.
     */
public String toString() {
    // For convenient reading of the string representation
    // all of the fields named according to the rfc 3280
    // (http://www.ietf.org/rfc/rfc3280.txt).
    StringBuilder result = new StringBuilder();
    result.append("X509CertSelector: \n[");
    if (this.certificateEquals != null) {
        result.append("\n  certificateEquals: ").append(certificateEquals);
    }
    if (this.serialNumber != null) {
        result.append("\n  serialNumber: ").append(serialNumber);
    }
    if (this.issuer != null) {
        result.append("\n  issuer: ").append(issuer);
    }
    if (this.subject != null) {
        result.append("\n  subject: ").append(subject);
    }
    if (this.subjectKeyIdentifier != null) {
        result.append("\n  subjectKeyIdentifier: ").append(Array.getBytesAsString(subjectKeyIdentifier));
    }
    if (this.authorityKeyIdentifier != null) {
        result.append("\n  authorityKeyIdentifier: ").append(Array.getBytesAsString(authorityKeyIdentifier));
    }
    if (this.certificateValid != null) {
        result.append("\n  certificateValid: ").append(certificateValid);
    }
    if (this.subjectPublicKeyAlgID != null) {
        result.append("\n  subjectPublicKeyAlgID: ").append(subjectPublicKeyAlgID);
    }
    if (this.privateKeyValid != null) {
        result.append("\n  privateKeyValid: ").append(privateKeyValid);
    }
    if (this.subjectPublicKey != null) {
        result.append("\n  subjectPublicKey: ").append(Array.getBytesAsString(subjectPublicKey));
    }
    if (this.keyUsage != null) {
        result.append("\n  keyUsage: \n  [");
        String[] kuNames = new String[] { "digitalSignature", "nonRepudiation", "keyEncipherment", "dataEncipherment", "keyAgreement", "keyCertSign", "cRLSign", "encipherOnly", "decipherOnly" };
        for (int i = 0; i < 9; i++) {
            if (keyUsage[i]) {
                result.append("\n    ").append(kuNames[i]);
            }
        }
        result.append("\n  ]");
    }
    if (this.extendedKeyUsage != null) {
        result.append("\n  extendedKeyUsage: ").append(extendedKeyUsage.toString());
    }
    result.append("\n  matchAllNames: ").append(matchAllNames);
    result.append("\n  pathLen: ").append(pathLen);
    if (this.subjectAltNames != null) {
        result.append("\n  subjectAltNames:  \n  [");
        for (int i = 0; i < 9; i++) {
            List<GeneralName> names = subjectAltNames[i];
            if (names != null) {
                int size = names.size();
                for (GeneralName generalName : names) {
                    result.append("\n    ").append(generalName.toString());
                }
            }
        }
        result.append("\n  ]");
    }
    if (this.nameConstraints != null) {
    }
    if (this.policies != null) {
        result.append("\n  policies: ").append(policies.toString());
    }
    if (this.pathToNames != null) {
        result.append("\n  pathToNames:  \n  [");
        for (GeneralName generalName : pathToNames) {
            result.append("\n    ").append(generalName.toString());
        }
    }
    result.append("\n]");
    return result.toString();
}
Also used : ASN1OctetString(org.apache.harmony.security.asn1.ASN1OctetString) GeneralName(org.apache.harmony.security.x509.GeneralName)

Example 93 with GeneralName

use of org.spongycastle.asn1.x509.GeneralName in project OpenAM by OpenRock.

the class ApprovalCallback method approve.

/*
    * Invoked by JSS protocol handler whenever ssl handshaking hits issue.
    * It validates reported issue if it can be ignored.
    *
    * @return <code>true</code> if the reported issue can be ignored.
    */
public boolean approve(X509Certificate cert, SSLCertificateApprovalCallback.ValidityStatus status) {
    ValidityItem item;
    Enumeration errors = status.getReasons();
    int reason;
    if (trustAllServerCerts) {
        return true;
    }
    if ((reqHost == null) && !errors.hasMoreElements()) {
        return true;
    }
    boolean approve = true;
    while (approve && errors.hasMoreElements()) {
        item = (SSLCertificateApprovalCallback.ValidityItem) errors.nextElement();
        reason = item.getReason();
        if (debug.messageEnabled()) {
            debug.message("ApprovalCallback: reason " + reason);
        }
        // bad domain -12276
        if (reason != ValidityStatus.BAD_CERT_DOMAIN) {
            approve = false;
        } else {
            String cn = null;
            try {
                String subjectDN = cert.getSubjectDN().getName();
                cn = new X500Name(subjectDN).getCommonName();
            } catch (Exception ex) {
                if (debug.messageEnabled()) {
                    debug.message("ApprovalCallback:", ex);
                }
                approve = false;
            }
            if (cn == null) {
                return false;
            }
            if (!sslTrustHosts.isEmpty()) {
                if (debug.messageEnabled()) {
                    debug.message("ApprovalCallback: server cert CN : " + cn);
                }
                if (sslTrustHosts.contains(cn.toLowerCase())) {
                    return true;
                }
            }
            if (resolveIPAddress) {
                try {
                    approve = InetAddress.getByName(cn).getHostAddress().equals(InetAddress.getByName(reqHost).getHostAddress());
                } catch (UnknownHostException ex) {
                    if (debug.messageEnabled()) {
                        debug.message("ApprovalCallback:", ex);
                    }
                    approve = false;
                }
            } else
                approve = false;
            if (!approve && checkSubjectAltName) {
                try {
                    X509CertImpl certImpl = new X509CertImpl(cert.getEncoded());
                    X509CertInfo cinfo = new X509CertInfo(certImpl.getTBSCertificate());
                    CertificateExtensions exts = (CertificateExtensions) cinfo.get(X509CertInfo.EXTENSIONS);
                    SubjectAlternativeNameExtension altNameExt = (SubjectAlternativeNameExtension) exts.get(SubjectAlternativeNameExtension.NAME);
                    if (altNameExt != null) {
                        GeneralNames names = (GeneralNames) altNameExt.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
                        Method meth = getMethod();
                        GeneralName generalname = null;
                        if (meth.getName().equals(OLD_METHOD_NAME)) {
                            // pre 1.4.2 implementation
                            Enumeration e = (Enumeration) meth.invoke(names, params);
                            for (; !approve && e.hasMoreElements(); ) {
                                approve = compareHosts((GeneralName) e.nextElement());
                            }
                        } else {
                            // post 1.4.2 implementation
                            Iterator i = (Iterator) meth.invoke(names, params);
                            for (; !approve && i.hasNext(); ) {
                                approve = compareHosts((GeneralName) i.next());
                            }
                        }
                    }
                } catch (Exception ex) {
                    return false;
                }
            }
        }
    }
    return approve;
}
Also used : Enumeration(java.util.Enumeration) UnknownHostException(java.net.UnknownHostException) X509CertInfo(sun.security.x509.X509CertInfo) SubjectAlternativeNameExtension(sun.security.x509.SubjectAlternativeNameExtension) CertificateExtensions(sun.security.x509.CertificateExtensions) X500Name(sun.security.x509.X500Name) Method(java.lang.reflect.Method) UnknownHostException(java.net.UnknownHostException) SSLCertificateApprovalCallback(org.mozilla.jss.ssl.SSLCertificateApprovalCallback) GeneralNames(sun.security.x509.GeneralNames) X509CertImpl(sun.security.x509.X509CertImpl) Iterator(java.util.Iterator) GeneralName(sun.security.x509.GeneralName)

Example 94 with GeneralName

use of org.spongycastle.asn1.x509.GeneralName in project OpenAM by OpenRock.

the class AMHostnameVerifier method verify.

public boolean verify(String hostname, SSLSession session) {
    if (trustAllServerCerts) {
        return true;
    }
    boolean approve = true;
    X509Certificate peercert = null;
    String cn = null;
    try {
        X509Certificate[] peercerts = (X509Certificate[]) session.getPeerCertificates();
        peercert = peercerts[0];
        String subjectDN = peercert.getSubjectDN().getName();
        cn = new X500Name(subjectDN).getCommonName();
    } catch (Exception ex) {
        debug.error("AMHostnameVerifier:" + ex.toString());
    }
    if (cn == null)
        return false;
    if (!sslTrustHosts.isEmpty()) {
        if (sslTrustHosts.contains(cn.toLowerCase())) {
            return true;
        }
    }
    if (resolveIPAddress) {
        try {
            approve = InetAddress.getByName(cn).getHostAddress().equals(InetAddress.getByName(hostname).getHostAddress());
        } catch (UnknownHostException ex) {
            if (debug.messageEnabled()) {
                debug.message("AMHostnameVerifier:", ex);
            }
            approve = false;
        }
    } else {
        approve = false;
    }
    if (checkSubjectAltName && !approve) {
        try {
            Iterator i = (Iterator) peercert.getSubjectAlternativeNames().iterator();
            for (; !approve && i.hasNext(); ) {
                approve = compareHosts((GeneralName) i.next(), hostname);
            }
        } catch (Exception ex) {
            return false;
        }
    }
    return approve;
}
Also used : UnknownHostException(java.net.UnknownHostException) Iterator(java.util.Iterator) X500Name(sun.security.x509.X500Name) GeneralName(sun.security.x509.GeneralName) X509Certificate(java.security.cert.X509Certificate) UnknownHostException(java.net.UnknownHostException)

Example 95 with GeneralName

use of org.spongycastle.asn1.x509.GeneralName in project nhin-d by DirectProject.

the class PKCS11Commands method createCSR.

@Command(name = "CreateCSR", usage = CREATE_CSR)
public void createCSR(String[] args) {
    final String alias = StringArrayUtil.getRequiredValue(args, 0);
    final String commonName = StringArrayUtil.getRequiredValue(args, 1);
    final String subjectAltName = StringArrayUtil.getRequiredValue(args, 2);
    final String keyUsage = StringArrayUtil.getRequiredValue(args, 3);
    // make sure we have a valid keyUsage
    if (!(keyUsage.compareToIgnoreCase("DigitalSignature") == 0 || keyUsage.compareToIgnoreCase("KeyEncipherment") == 0 || keyUsage.compareToIgnoreCase("DualUse") == 0)) {
        System.out.println("Invalid key usage.");
        return;
    }
    final Vector<String> additionalRDNFields = new Vector<String>();
    int cnt = 4;
    String rdnField;
    do {
        rdnField = StringArrayUtil.getOptionalValue(args, cnt++, "");
        if (!StringUtils.isEmpty(rdnField))
            additionalRDNFields.add(rdnField);
    } while (!StringUtils.isEmpty(rdnField));
    try {
        final KeyStore ks = mgr.getKS();
        if (!ks.containsAlias(alias)) {
            System.out.println("Entry with key name " + alias + " does not exist.");
            return;
        }
        final X509Certificate storedCert = (X509Certificate) ks.getCertificate(alias);
        if (storedCert == null) {
            System.out.println("Key name " + alias + " does not contain a certificate that can be exported.  This key may not be an RSA key pair.");
            return;
        }
        final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
        if (privKey == null) {
            System.out.println("Failed to object private key.  This key may not be an RSA key pair.");
            return;
        }
        // create the CSR
        //  create the extensions that we want
        final X509ExtensionsGenerator extsGen = new X509ExtensionsGenerator();
        // Key Usage
        int usage;
        if (keyUsage.compareToIgnoreCase("KeyEncipherment") == 0)
            usage = KeyUsage.keyEncipherment;
        else if (keyUsage.compareToIgnoreCase("DigitalSignature") == 0)
            usage = KeyUsage.digitalSignature;
        else
            usage = KeyUsage.keyEncipherment | KeyUsage.digitalSignature;
        extsGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(usage));
        // Subject Alt Name
        int nameType = subjectAltName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
        final GeneralNames altName = new GeneralNames(new GeneralName(nameType, subjectAltName));
        extsGen.addExtension(X509Extensions.SubjectAlternativeName, false, altName);
        // Extended Key Usage
        final Vector<KeyPurposeId> purposes = new Vector<KeyPurposeId>();
        purposes.add(KeyPurposeId.id_kp_emailProtection);
        extsGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(purposes));
        // Basic constraint
        final BasicConstraints bc = new BasicConstraints(false);
        extsGen.addExtension(X509Extensions.BasicConstraints, true, bc);
        // create the extension requests
        final X509Extensions exts = extsGen.generate();
        final ASN1EncodableVector attributes = new ASN1EncodableVector();
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(exts.toASN1Object()));
        attributes.add(attribute);
        final DERSet requestedAttributes = new DERSet(attributes);
        // create the DN
        final StringBuilder dnBuilder = new StringBuilder("CN=").append(commonName);
        for (String field : additionalRDNFields) dnBuilder.append(",").append(field);
        final X500Principal subjectPrin = new X500Principal(dnBuilder.toString());
        final X509Principal xName = new X509Principal(true, subjectPrin.getName());
        // create the CSR
        final PKCS10CertificationRequest request = new PKCS10CertificationRequest("SHA256WITHRSA", xName, storedCert.getPublicKey(), requestedAttributes, privKey, ks.getProvider().getName());
        final byte[] encodedCSR = request.getEncoded();
        final String csrString = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + Base64.encodeBase64String(encodedCSR) + "-----END CERTIFICATE REQUEST-----";
        final File csrFile = new File(alias + "-CSR.pem");
        FileUtils.writeStringToFile(csrFile, csrString);
        System.out.println("CSR written to " + csrFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to create CSR : " + e.getMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) Attribute(org.bouncycastle.asn1.x509.Attribute) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERSet(org.bouncycastle.asn1.DERSet) X509Principal(org.bouncycastle.jce.X509Principal) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) X509ExtensionsGenerator(org.bouncycastle.asn1.x509.X509ExtensionsGenerator) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) File(java.io.File) Command(org.nhindirect.common.tooling.Command)

Aggregations

GeneralName (org.bouncycastle.asn1.x509.GeneralName)125 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)59 IOException (java.io.IOException)49 DERIA5String (org.bouncycastle.asn1.DERIA5String)36 ArrayList (java.util.ArrayList)34 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)32 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)31 X500Name (org.bouncycastle.asn1.x500.X500Name)30 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)28 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)27 X509Certificate (java.security.cert.X509Certificate)25 DEROctetString (org.bouncycastle.asn1.DEROctetString)24 List (java.util.List)21 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)19 Date (java.util.Date)18 GeneralName (org.apache.harmony.security.x509.GeneralName)18 DirectoryString (org.bouncycastle.asn1.x500.DirectoryString)18 DERSequence (org.bouncycastle.asn1.DERSequence)17 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)16 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)16