Example usage for java.security.cert X509Certificate getSubjectX500Principal

List of usage examples for java.security.cert X509Certificate getSubjectX500Principal

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSubjectX500Principal.

Prototype

public X500Principal getSubjectX500Principal() 

Source Link

Document

Returns the subject (subject distinguished name) value from the certificate as an X500Principal .

Usage

From source file:edu.vt.middleware.ldap.ssl.DefaultHostnameVerifier.java

/**
 * Returns the CNs from the supplied certificate.
 *
 * @param  cert  to get CNs from//from   w  w  w . j  av  a2s  .  com
 *
 * @return  CNs
 */
private String[] getCNs(final X509Certificate cert) {
    final List<String> names = new ArrayList<String>();
    final String subjectPrincipal = cert.getSubjectX500Principal().toString();
    if (subjectPrincipal != null) {
        try {
            final LdapName subjectDn = new LdapName(subjectPrincipal);
            for (Rdn rdn : subjectDn.getRdns()) {
                final Attributes attrs = rdn.toAttributes();
                final NamingEnumeration<String> ids = attrs.getIDs();
                while (ids.hasMore()) {
                    final String id = ids.next();
                    if (id.toLowerCase().equals("cn") || id.toLowerCase().equals("commonname")
                            || id.toLowerCase().equals("2.5.4.3")) {
                        final Object value = attrs.get(id).get();
                        if (value != null) {
                            if (value instanceof String) {
                                names.add((String) value);
                            } else if (value instanceof Attribute) {
                                // for multi value RDNs the first value is used
                                final Object multiValue = ((Attribute) value).get();
                                if (multiValue != null && multiValue instanceof String) {
                                    names.add((String) multiValue);
                                }
                            }
                        }
                    }
                }
            }
        } catch (NamingException e) {
            if (this.logger.isWarnEnabled()) {
                this.logger.warn("Could not get distinguished name from subject " + subjectPrincipal, e);
            }
        }
    }
    return names.toArray(new String[names.size()]);
}

From source file:de.vanita5.twittnuker.util.net.ssl.AbstractCheckSignatureVerifier.java

public static String[] getCNs(final X509Certificate cert) {
    final LinkedList<String> cnList = new LinkedList<String>();
    /*//from w  w w.ja  v a  2  s.c  om
     * Sebastian Hauer's original StrictSSLProtocolSocketFactory used
     * getName() and had the following comment:
     *
     * Parses a X.500 distinguished name for the value of the "Common Name"
     * field. This is done a bit sloppy right now and should probably be
     * done a bit more according to <code>RFC 2253</code>.
     *
     * I've noticed that toString() seems to do a better job than getName()
     * on these X500Principal objects, so I'm hoping that addresses
     * Sebastian's concern.
     *
     * For example, getName() gives me this:
     * 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
     *
     * whereas toString() gives me this: EMAILADDRESS=juliusdavies@cucbc.com
     *
     * Looks like toString() even works with non-ascii domain names! I
     * tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
     */

    final String subjectPrincipal = cert.getSubjectX500Principal().toString();
    final StringTokenizer st = new StringTokenizer(subjectPrincipal, ",+");
    while (st.hasMoreTokens()) {
        final String tok = st.nextToken().trim();
        if (tok.length() > 3) {
            if (tok.substring(0, 3).equalsIgnoreCase("CN=")) {
                cnList.add(tok.substring(3));
            }
        }
    }
    if (!cnList.isEmpty()) {
        final String[] cns = new String[cnList.size()];
        cnList.toArray(cns);
        return cns;
    } else
        return null;
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESService.java

private CMSSignedDataGenerator createCMSSignedDataGenerator(ContentSigner contentSigner,
        DigestCalculatorProvider digestCalculatorProvider, SignatureParameters parameters,
        CAdESProfileBES cadesProfile, boolean includeUnsignedAttributes, CMSSignedData originalSignedData)
        throws IOException {

    try {/*from  w ww. j ava2 s.c  o m*/

        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

        X509Certificate signerCertificate = parameters.getSigningCertificate();

        X509CertificateHolder certHolder = new X509CertificateHolder(signerCertificate.getEncoded());

        SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(
                digestCalculatorProvider);

        sigInfoGeneratorBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(
                new AttributeTable(cadesProfile.getSignedAttributes(parameters))));

        sigInfoGeneratorBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(
                (includeUnsignedAttributes) ? new AttributeTable(cadesProfile.getUnsignedAttributes(parameters))
                        : null));

        SignerInfoGenerator sigInfoGen = sigInfoGeneratorBuilder.build(contentSigner, certHolder);

        generator.addSignerInfoGenerator(sigInfoGen);
        if (originalSignedData != null) {
            generator.addSigners(originalSignedData.getSignerInfos());
        }

        Collection<X509Certificate> certs = new ArrayList<X509Certificate>();
        certs.add(parameters.getSigningCertificate());

        if (parameters.getCertificateChain() != null) {
            for (X509Certificate c : parameters.getCertificateChain()) {
                if (!c.getSubjectX500Principal()
                        .equals(parameters.getSigningCertificate().getSubjectX500Principal())) {
                    certs.add(c);
                }
            }
        }

        JcaCertStore certStore = new JcaCertStore(certs);
        generator.addCertificates(certStore);
        if (originalSignedData != null) {
            generator.addCertificates(originalSignedData.getCertificates());
        }

        return generator;

    } catch (CMSException e) {
        throw new IOException(e);
    } catch (CertificateEncodingException e) {
        throw new IOException(e);
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }

}

From source file:org.openanzo.client.AnzoTrustManager.java

private void handleCertificateException(CertificateException ce, X509Certificate[] chain)
        throws CertificateException {
    if (trustAll) {
        return;//w w w  .  j  a  v a  2s .  co m
    }

    System.err.println(ce.getMessage());
    System.err.println("Certificate Information: \n");
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(chain[0].getNotBefore().getTime());
    System.err.println("Creation Date: " + MONTHS[cal.get(Calendar.MONTH)] + " "
            + cal.get(Calendar.DAY_OF_MONTH) + ", " + cal.get(Calendar.YEAR));
    //System.err.println("Entry type: " + chain[0].getType());
    System.err.println("Certificate chain length: " + chain.length);

    // print some information about the certificate(s) that failed
    int i = 1;
    for (X509Certificate cert : chain) {
        System.err.println("Certificate[" + i++ + "]:");
        System.err.println("Owner: " + cert.getSubjectX500Principal().toString());
        System.err.println("Issuer: " + cert.getIssuerX500Principal().toString());

        String serialNum = new String(Hex.encodeHex(cert.getSerialNumber().toByteArray()));
        System.err.println("Serial Number: " + serialNum);
        System.err.println(
                "Valid from: " + cert.getNotBefore().toString() + " until: " + cert.getNotAfter().toString());
        System.err.println("Certificate fingerprints: ");
        try {
            byte[] sig = cert.getEncoded();
            System.err.println("\tMD5: " + getHash(sig, "MD5"));
            System.err.println("\tSHA1: " + getHash(sig, "SHA1"));
        } catch (NoSuchAlgorithmException e) {
        }
        System.err.println("\tSignature Algorithm Name: " + cert.getSigAlgName());
        System.err.println("\tVersion: " + cert.getVersion());
        System.err.println("-----------------------------------------------------");
    }
    System.err.println("Would you like to accept this certificate? (o)nce, (a)lways, (n)o");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line = "";
    try {
        line = in.readLine();
    } catch (IOException e) {
        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
        System.exit(1);
    }
    if (Character.toLowerCase(line.charAt(0)) == 'o') {
        return;
    } else if (Character.toLowerCase(line.charAt(0)) == 'a') {
        try {
            String truststoreType = System.getProperty("javax.net.ssl.trustStoreType", "JCEKS");
            String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_PWORD);

            String truststorePath = System.getProperty("javax.net.ssl.trustStore");
            if (truststorePath == null) { // there is no trust store location in the user's settings.trig file
                String userHome = System.getProperty("user.home");
                if (userHome == null)
                    throw new AnzoException(ExceptionConstants.CLIENT.FAILED_INITIALIZE_TRUST_MANAGER,
                            "User's home directory is not specified");
                File truststoreFile = new File(new File(userHome, ANZO_DIR), DEFAULT_CLIENT_TRUST);
                truststorePath = truststoreFile.getCanonicalPath();
                if (!truststoreFile.exists())
                    openTruststore(truststoreType, truststorePath, truststorePassword);
            } else {
                truststorePath = CommandContext.preprocessString(truststorePath);
                File truststoreFile = new File(truststorePath);

                if (!truststoreFile.exists()) {
                    System.err.println("Could not find the specified trust store file at:");
                    System.err.println(truststoreFile.getCanonicalPath());
                    System.err.println(
                            "The trust store file is used for permanently trusting server certificates that");
                    System.err.println("are not trusted by default.");
                    System.err.println(
                            "Would you like to create a new trust store file at the specified location?");
                    System.err.println("(y)es, (n)o");
                    try {
                        line = in.readLine();
                    } catch (IOException e) {
                        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
                        System.exit(1);
                    }
                    if (Character.toLowerCase(line.charAt(0)) == 'y')
                        openTruststore(truststoreType, truststorePath, truststorePassword);
                    else
                        System.exit(1);
                }
            }

            KeystoreUtils.addTrustedCert(truststorePath, truststoreType, truststorePassword,
                    "imported_" + System.currentTimeMillis(), chain[0]);
        } catch (AnzoException ae) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(ae, showTrace);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
            System.exit(1);
        }
    } else {
        System.exit(1); // if the user does not want to trust the certificate then exit
    }
}

From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java

private static boolean isSelfSigned(X509Certificate certificate) {

    return certificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal());
}

From source file:be.fedict.eid.idp.sp.protocol.saml2.artifact.ArtifactServiceClient.java

/**
 * If set, unilateral TLS authentication will occur, verifying the server
 * {@link X509Certificate} specified against the {@link PublicKey}.
 * //from  w  w w .j av a  2 s. c  om
 * @param publicKey
 *            public key to validate server TLS certificate against.
 */
public void setServicePublicKey(final PublicKey publicKey) {

    // Create TrustManager
    TrustManager[] trustManager = { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {

            return null;
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            X509Certificate serverCertificate = chain[0];
            LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString());
            LOG.debug("authentication type: " + authType);
            if (null == publicKey) {
                return;
            }

            try {
                serverCertificate.verify(publicKey);
                LOG.debug("valid server certificate");
            } catch (InvalidKeyException e) {
                throw new CertificateException("Invalid Key");
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException("No such algorithm");
            } catch (NoSuchProviderException e) {
                throw new CertificateException("No such provider");
            } catch (SignatureException e) {
                throw new CertificateException("Wrong signature");
            }
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            throw new CertificateException("this trust manager cannot be used as server-side trust manager");
        }
    } };

    // Create SSL Context
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());

        // Setup TrustManager for validation
        Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext();
        requestContext.put(JAXWSProperties.SSL_SOCKET_FACTORY, sslContext.getSocketFactory());

    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:org.globus.myproxy.MyProxy.java

private static String opensslHash(X509Certificate cert) {
    try {/*from   w  ww  . j  a  v  a  2  s .  c  om*/
        return openssl_X509_NAME_hash(cert.getSubjectX500Principal());
    } catch (Exception e) {
        throw new Error("MD5 isn't available!", e);
    }
}

From source file:be.fedict.trust.linker.PublicKeyTrustLinker.java

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {
    if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
        LOG.debug("child certificate issuer not the same as the issuer certificate subject");
        LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal());
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
        LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal());
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                "child certificate issuer not the same as the issuer certificate subject");
    }/*  w  w w . ja v  a2 s . c o  m*/
    try {
        childCertificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.debug("verification error: " + e.getMessage(), e);
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_SIGNATURE,
                "verification error: " + e.getMessage());
    }

    algorithmPolicy.checkSignatureAlgorithm(childCertificate.getSigAlgOID(), validationDate);

    if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) {
        LOG.warn("child certificate validity end is after certificate validity end");
        LOG.warn("child certificate validity end: " + childCertificate.getNotAfter());
        LOG.warn("certificate validity end: " + certificate.getNotAfter());
    }
    if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) {
        LOG.warn("child certificate validity begin before certificate validity begin");
        LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore());
        LOG.warn("certificate validity begin: " + certificate.getNotBefore());
    }
    if (true == validationDate.before(childCertificate.getNotBefore())) {
        LOG.debug("certificate is not yet valid");
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate is not yet valid");
    }
    if (true == validationDate.after(childCertificate.getNotAfter())) {
        LOG.debug("certificate already expired");
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate already expired");
    }
    if (-1 == certificate.getBasicConstraints()) {
        LOG.debug("certificate not a CA: " + certificate.getSubjectX500Principal());
        /*
         * http://www.valicert.com/ Root CA has no CA flag set. Actually
         * this is in violation with 4.2.1.10 Basic Constraints of RFC2459.
         */
        try {
            certificate.verify(certificate.getPublicKey());
            LOG.warn("allowing self-signed Root CA without CA flag set");
        } catch (Exception e) {
            throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST, "certificate not a CA");
        }
    }
    if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) {
        LOG.debug("child should not be a CA");
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST, "child should not be a CA");
    }

    /*
     * SKID/AKID sanity check
     */
    boolean isCa = isCa(certificate);
    boolean isChildCa = isCa(childCertificate);

    byte[] subjectKeyIdentifierData = certificate.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    byte[] authorityKeyIdentifierData = childCertificate
            .getExtensionValue(Extension.authorityKeyIdentifier.getId());

    if (isCa && null == subjectKeyIdentifierData) {
        LOG.debug("certificate is CA and MUST contain a Subject Key Identifier");
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                "certificate is CA and  MUST contain a Subject Key Identifier");
    }

    if (isChildCa && null == authorityKeyIdentifierData && null != subjectKeyIdentifierData) {
        LOG.error("child certificate is CA and MUST contain an Authority Key Identifier");
        // return new TrustLinkerResult(false,
        // TrustLinkerResultReason.INVALID_TRUST,
        // "child certificate is CA and MUST contain an Authority Key Identifier");
    }

    if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) {
        AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier
                .getInstance(JcaX509ExtensionUtils.parseExtensionValue(authorityKeyIdentifierData));
        SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier
                .getInstance(JcaX509ExtensionUtils.parseExtensionValue(subjectKeyIdentifierData));
        if (!Arrays.equals(authorityKeyIdentifier.getKeyIdentifier(),
                subjectKeyIdentifier.getKeyIdentifier())) {
            LOG.debug(
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
            throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
        }
    }

    /*
     * We don't check pathLenConstraint since this one is only there to
     * protect the PKI business.
     */
    /*
     * Keep in mind that this trust linker can never return TRUSTED.
     */
    return TrustLinkerResult.UNDECIDED;
}

From source file:cz.hobrasoft.pdfmu.operation.OperationInspect.java

private CertificateResult showCertInfo(X509Certificate cert) {
    CertificateResult certRes = new CertificateResult();

    { // Self-signed?
        X500Principal principalSubject = cert.getSubjectX500Principal();
        X500Principal principalIssuer = cert.getIssuerX500Principal();
        boolean selfSigned = principalSubject.equals(principalIssuer);
        to.println(String.format("Self-signed: %s", (selfSigned ? "Yes" : "No")));
        certRes.selfSigned = selfSigned;
    }//from w  w  w .j a  va 2  s . c  o  m

    // Note: More attributes may be available by more direct processing of `cert`
    // than by using `CertificateInfo.get*Fields`.
    { // Subject
        to.indentMore("Subject:");
        certRes.subject = showX500Name(CertificateInfo.getSubjectFields(cert));
        to.indentLess();
    }
    { // Issuer
        to.indentMore("Issuer:");
        certRes.issuer = showX500Name(CertificateInfo.getIssuerFields(cert));
        to.indentLess();
    }

    return certRes;
}