Example usage for java.security.cert X509Certificate getSubjectDN

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

Introduction

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

Prototype

public abstract Principal getSubjectDN();

Source Link

Document

Denigrated, replaced by #getSubjectX500Principal() .

Usage

From source file:org.xdi.util.EasyX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],
 *      String authType)/*w  ww  .j  a va2s  .c  o  m*/
 */
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    if (certificates != null && LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certificates.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certificates[i]);
        }
    }
    if (certificates != null && (certificates.length == 1)) {
        certificates[0].checkValidity();
    } else {
        List<X509Certificate> certs = new ArrayList<X509Certificate>();
        if (certificates != null) {
            certs.addAll(Arrays.asList(certificates));
        }
        X509Certificate certChain = certs.get(0);
        certs.remove(certChain);
        LinkedList<X509Certificate> chainList = new LinkedList<X509Certificate>();
        chainList.add(certChain);
        Principal certIssuer = certChain.getIssuerDN();
        Principal certSubject = certChain.getSubjectDN();
        while (!certs.isEmpty()) {
            List<X509Certificate> tempcerts = new ArrayList<X509Certificate>();
            tempcerts.addAll(certs);
            for (X509Certificate cert : tempcerts) {
                if (cert.getIssuerDN().equals(certSubject)) {
                    chainList.addFirst(cert);
                    certSubject = cert.getSubjectDN();
                    certs.remove(cert);
                    continue;
                }

                if (cert.getSubjectDN().equals(certIssuer)) {
                    chainList.addLast(cert);
                    certIssuer = cert.getIssuerDN();
                    certs.remove(cert);
                    continue;
                }
            }
        }
        standardTrustManager.checkServerTrusted(chainList.toArray(new X509Certificate[] {}), authType);

    }
}

From source file:edu.vt.middleware.crypt.KeyStoreCli.java

/**
 * Prints a string representation of the given certificate to STDOUT. For an
 * X.509 certificate, prints important fields.
 *
 * @param  cert  Certificate to print./*from  w  w  w .  j  a v a  2 s  .c  o m*/
 *
 * @throws  Exception  On print errors.
 */
protected void printCertificate(final Certificate cert) throws Exception {
    if (cert instanceof X509Certificate) {
        final X509Certificate xCert = (X509Certificate) cert;
        final byte[] encodedCert = xCert.getEncoded();
        System.out.println("Subject: " + xCert.getSubjectDN());
        System.out.println("Issuer: " + xCert.getIssuerDN());
        System.out.println("Serial: " + hexConv.fromBytes(xCert.getSerialNumber().toByteArray()));
        System.out.println("Valid not before: " + xCert.getNotBefore());
        System.out.println("Valid not after: " + xCert.getNotAfter());
        System.out.println("MD5 fingerprint: " + md5.digest(encodedCert, hexConv));
        System.out.println("SHA1 fingerprint: " + sha1.digest(encodedCert, hexConv));
    } else {
        System.out.println(cert);
    }
}

From source file:org.nuxeo.ecm.platform.signature.core.user.CUserServiceImpl.java

private String getUserCertInfo(KeyStore keystore, DocumentModel user) throws CertException, ClientException {
    String userCertInfo = null;/*from w  w w.  j a v  a  2  s . com*/
    if (null != keystore) {
        String userID = (String) user.getPropertyValue("user:username");
        AliasWrapper alias = new AliasWrapper(userID);
        X509Certificate certificate = getCertService().getCertificate(keystore, alias.getId(AliasType.CERT));
        userCertInfo = certificate.getSubjectDN() + " valid till: " + certificate.getNotAfter();
    }
    return userCertInfo;
}

From source file:org.viafirma.nucleo.validacion.ValidadorHandler.java

/**
 * Valida el certificado indicado. Utilizando segn el tipo validacin OCSP
 * o CRL./*from www. j  a  v  a2  s .  c  om*/
 * 
 * @param certificadoX509
 * @return
 */
public CodigoError validar(X509Certificate certificadoX509) {
    // Si el protocolo es OCSP....
    if (isOCSPProtocol(certificadoX509)) {
        if (log.isDebugEnabled())
            log.debug("Validando con OCSP el certificado : " + certificadoX509.getSubjectDN().getName());
        try {
            return ocspValidationHandler.validarOCSP(certificadoX509);
        } catch (CertPathValidatorException e) {
            log.warn(e.getMessage());
            return CodigoError.ERROR_OCSP_INTERNAL_ERROR;
        }
    } else {
        // el certificado sera validado utilizando el mtodo de acceso a
        // CRLs
        if (log.isDebugEnabled())
            log.debug("Validando certificado : " + certificadoX509.getSubjectDN().getName());
        return crlValidationHandler.validarCRL(certificadoX509);
    }
}

From source file:org.soasecurity.mutual.ssl.filter.MutualSSLFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    log.debug("Mutual SSL Filter is invoked.");

    X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");

    if (certs != null) {

        // client certificate must be first certificate in the chain
        X509Certificate clientCert = certs[0];

        // encode certificate
        String certificateData = "";
        try {// ww w  .j av a 2  s .  c om
            certificateData = new String(Base64.encodeBase64(clientCert.getEncoded()));
        } catch (CertificateEncodingException e) {
            log.error("Error while encoding the certificate", e);
        }

        Principal principal = clientCert.getSubjectDN();

        String subjectDN = principal.getName();

        log.debug("Mutual Authentication is success full with subject : " + subjectDN);

        // creating new wrapper to set a new parameter
        X509HTTPServletWrapper wrapper = new X509HTTPServletWrapper((HttpServletRequest) request, subjectDN,
                certificateData);

        chain.doFilter(wrapper, response);

    } else {

        chain.doFilter(request, response);
    }
}

From source file:jenkins.plugins.publish_over_ftp.BapFtpHostConfiguration.java

public FTPClient createFTPClient() throws GeneralSecurityException, FileNotFoundException, IOException {
    if (useFtpOverTls) {
        FTPSClient c = new FTPSClient(false);

        KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
        String trustStorePath = System.getProperty("javax.net.ssl.trustStore");
        if (trustStorePath != null) {
            String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
            if (trustStorePassword != null) {
                ts.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());
            } else {
                ts.load(new FileInputStream(trustStorePath), null);
            }/*from  w  ww .  j a va 2  s . co m*/
        } else {
            ts.load(null);
        }

        if (trustedCertificate != null) {
            InputStream certStream = new ByteArrayInputStream(trustedCertificate.getBytes());
            X509Certificate x509certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                    .generateCertificate(certStream);
            ts.setCertificateEntry(x509certificate.getSubjectDN().getName(), x509certificate);
        }

        c.setTrustManager(TrustManagerUtils.getDefaultTrustManager(ts));

        return c;
    }
    return new FTPClient();
}

From source file:gov.nist.toolkit.soap.axis2.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() throws IOException {
    try {/*from w  ww. ja v  a 2  s.c  o m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new IOException("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new IOException("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new IOException("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new IOException("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.acegisecurity.providers.x509.cache.EhCacheBasedX509UserCache.java

public UserDetails getUserFromCache(X509Certificate userCert) {
    Element element = null;/*from   w  w w.j  a  v  a  2 s.com*/

    try {
        element = cache.get(userCert);
    } catch (CacheException cacheException) {
        throw new DataRetrievalFailureException("Cache failure: " + cacheException.getMessage());
    }

    if (logger.isDebugEnabled()) {
        String subjectDN = "unknown";

        if ((userCert != null) && (userCert.getSubjectDN() != null)) {
            subjectDN = userCert.getSubjectDN().toString();
        }

        logger.debug("X.509 Cache hit. SubjectDN: " + subjectDN);
    }

    if (element == null) {
        return null;
    } else {
        return (UserDetails) element.getValue();
    }
}

From source file:org.cesecore.certificates.ca.internal.CertificateValidity.java

public static void checkPrivateKeyUsagePeriod(final X509Certificate cert, final Date checkDate)
        throws CAOfflineException {
    if (cert != null) {
        final PrivateKeyUsagePeriod pku = CertTools.getPrivateKeyUsagePeriod(cert);
        if (pku != null) {
            final ASN1GeneralizedTime notBefore = pku.getNotBefore();
            final Date pkuNotBefore;
            final Date pkuNotAfter;
            try {
                if (notBefore == null) {
                    pkuNotBefore = null;
                } else {
                    pkuNotBefore = notBefore.getDate();
                }//from w ww  .  j a  v a  2  s . c  o m
                if (log.isDebugEnabled()) {
                    log.debug("PrivateKeyUsagePeriod.notBefore is " + pkuNotBefore);
                }
                if (pkuNotBefore != null && checkDate.before(pkuNotBefore)) {
                    final String msg = intres.getLocalizedMessage("createcert.privatekeyusagenotvalid",
                            pkuNotBefore.toString(), cert.getSubjectDN().toString());
                    if (log.isDebugEnabled()) {
                        log.debug(msg);
                    }
                    throw new CAOfflineException(msg);
                }
                final ASN1GeneralizedTime notAfter = pku.getNotAfter();

                if (notAfter == null) {
                    pkuNotAfter = null;
                } else {
                    pkuNotAfter = notAfter.getDate();
                }
            } catch (ParseException e) {
                throw new IllegalStateException("Could not parse dates.", e);
            }
            if (log.isDebugEnabled()) {
                log.debug("PrivateKeyUsagePeriod.notAfter is " + pkuNotAfter);
            }
            if (pkuNotAfter != null && checkDate.after(pkuNotAfter)) {
                final String msg = intres.getLocalizedMessage("createcert.privatekeyusageexpired",
                        pkuNotAfter.toString(), cert.getSubjectDN().toString());
                if (log.isDebugEnabled()) {
                    log.debug(msg);
                }
                throw new CAOfflineException(msg);
            }
        } else if (log.isDebugEnabled()) {
            log.debug("No PrivateKeyUsagePeriod available in certificate.");
        }
    } else if (log.isDebugEnabled()) {
        log.debug("No CA certificate available, not checking PrivateKeyUsagePeriod.");
    }
}

From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

/**
 * Prints Issuer/SubjectDN/SerialNumber of all x509 certificates that can be found in the CMSSignedData
 * /*from  w  w  w.jav a2  s . com*/
 * @throws CertificateException
 */
private void printAllX509Certificates() throws CertificateException {

    // Find all available certificates with getMatches(null)
    Iterator<?> certIt = cmsSignedData.getCertificates().getMatches(null).iterator();
    int i = 0;

    while (certIt.hasNext()) {
        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
        System.out.println("X509 Certificate #" + ++i);
        System.out.println("X509 Issuer: " + cert.getIssuerDN());
        System.out.println("X509 Subject DN: " + cert.getSubjectDN());
        System.out.println("X509 SerialNumber: " + cert.getSerialNumber());
        System.out.println("SignerCert: " + (cert.getBasicConstraints() == -1 ? "Yes" : "No"));
        System.out.println();
    }
}