Example usage for java.security.cert X509Certificate getIssuerDN

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

Introduction

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

Prototype

public abstract Principal getIssuerDN();

Source Link

Document

Denigrated, replaced by #getIssuerX500Principal() .

Usage

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

/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],
 *      String authType)/*ww  w  .jav a2  s  . co  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:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private TrustManager[] setupTrustManagers()
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
    // This is the cert authority that validates server's cert, so we need to put it in our
    // trustStore.
    if (_serverCACertFile != null) {
        LOGGER.info("Initializing trust store from {}", _serverCACertFile);
        FileInputStream is = new FileInputStream(new File(_serverCACertFile));
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);//from w w  w  .j  av a2 s  .c o  m
        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        int i = 0;
        while (is.available() > 0) {
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
            LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16),
                    cert.getIssuerDN().toString());

            String serverKey = "https-server-" + i;
            trustStore.setCertificateEntry(serverKey, cert);
            i++;
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE);
        tmf.init(trustStore);
        LOGGER.info("Successfully initialized trust store");
        return tmf.getTrustManagers();
    }
    // Server verification disabled. Trust all servers
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    return trustAllCerts;
}

From source file:org.keysupport.shibboleth.idp.x509.X509AuthServlet.java

/** {@inheritDoc} */
@Override//  w ww  .j a v a2 s . com
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        final String key = ExternalAuthentication.startExternalAuthentication(httpRequest);

        final X509Certificate[] certs = (X509Certificate[]) httpRequest
                .getAttribute("javax.servlet.request.X509Certificate");
        log.debug("{} X.509 Certificate(s) found in request", certs != null ? certs.length : 0);

        if (certs == null || certs.length < 1) {
            log.error("No X.509 Certificates found in request");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    AuthnEventIds.NO_CREDENTIALS);
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        final X509Certificate cert = certs[0];
        log.debug("End-entity X.509 certificate found with subject '{}', issued by '{}'",
                cert.getSubjectDN().getName(), cert.getIssuerDN().getName());

        if (trustEngine != null) {
            try {
                final BasicX509Credential cred = new BasicX509Credential(cert);
                cred.setEntityCertificateChain(Arrays.asList(certs));
                if (trustEngine.validate(cred, new CriteriaSet())) {
                    log.debug("Trust engine validated X.509 certificate");
                } else {
                    log.warn("Trust engine failed to validate X.509 certificate");
                    httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                            AuthnEventIds.INVALID_CREDENTIALS);
                    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                    return;
                }
            } catch (final SecurityException e) {
                log.error("Exception raised by trust engine", e);
                httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_EXCEPTION_KEY, e);
                ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                return;
            }
        }

        final String passthrough = httpRequest.getParameter(PASSTHROUGH_PARAM);
        if (passthrough != null && Boolean.parseBoolean(passthrough)) {
            log.debug("Setting UI passthrough cookie");
            final Cookie cookie = new Cookie(PASSTHROUGH_PARAM, "1");
            cookie.setPath(httpRequest.getContextPath());
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setSecure(true);
            httpResponse.addCookie(cookie);
        }

        final Subject subject = new Subject();
        subject.getPublicCredentials().add(cert);
        subject.getPrincipals().add(cert.getSubjectX500Principal());

        httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);

        //         final String revokeConsent = httpRequest
        //               .getParameter(ProfileInterceptorFlowDescriptor.REVOKE_CONSENT_PARAM);
        //         if (revokeConsent != null
        //               && ("1".equals(revokeConsent) || "true"
        //                     .equals(revokeConsent))) {
        //            httpRequest.setAttribute(
        //                  ExternalAuthentication.REVOKECONSENT_KEY, Boolean.TRUE);
        //         }

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

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   ww w. jav  a 2 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();
    }
}

From source file:org.viafirma.nucleo.autenticacion.imp.AutenticacionAppletBridgeImp.java

/**
 * Recupera el certificado enviado por el navegador y lo almacena en el
 * nucleo./* w w w  . jav  a  2s .com*/
 * 
 * Proceso:
 * 
 * <pre>
 * 1.- Recupera el XmlSignature desde el parametro message
 * 2.- Desde el XmlSignature recupera el X509Certificado
 * 3.- Se lo pasa al ncleo para que lo valide.
 * </pre>
 * 
 * @param request
 * @param response
 * @throws ServletException
 */
private void recuperarCertificado(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {

    try {
        // certificado en xml codificado en base 64
        String xmldoc_b64 = request.getParameter("message");

        // recupero el identificador de sessin con el que posteriormente
        // poder identificar este objeto.
        String sessionID = request.getParameter("sessionID");

        XmlSignUtil xmlSignParser = XmlSignUtil.getInstance();
        // recupero el XmlSignature generado por el applet de autenticacin
        // ( Siempre tiene que aparecer 1
        X509Certificate certificadoX509 = xmlSignParser.parseCertificado(xmldoc_b64).get(0);

        // mostramos el certificado recuperado
        if (log.isDebugEnabled()) {
            log.debug("Recuperado certificado " + certificadoX509.getIssuerDN().getName());
        }

        // enviamos el certificado al ncleo para que este compruebe la
        // validez del mismo
        Nucleo nucleo = Nucleo.getInstance();
        // almacena el certificado recuperado en el ncleo para su
        // procesamiento posterior.
        nucleo.cachearCertificado(sessionID, certificadoX509);

    } catch (Exception e) {
        throw new ServletException(e);
    }

}

From source file:com.thoughtworks.go.security.AuthSSLX509TrustManagerFactory.java

private void logKeyStore(KeyStore store) throws KeyStoreException {
    Enumeration aliases = store.aliases();
    while (aliases.hasMoreElements()) {
        String alias = (String) aliases.nextElement();
        LOG.debug("Trusted certificate '" + alias + "':");
        Certificate trustedcert = store.getCertificate(alias);
        if (trustedcert != null && trustedcert instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) trustedcert;
            LOG.trace("  Subject DN: " + cert.getSubjectDN());
            LOG.trace("  Signature Algorithm: " + cert.getSigAlgName());
            LOG.trace("  Valid from: " + cert.getNotBefore());
            LOG.trace("  Valid until: " + cert.getNotAfter());
            LOG.trace("  Issuer: " + cert.getIssuerDN());
        }//from w  w w  .  j a  v a 2  s.c o  m
    }
}

From source file:org.glite.slcs.httpclient.ssl.ExtendedX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String
 *      authType)//from   w  ww. ja v  a 2s .c o  m
 */
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Certificate chain:");
        if (chain != null) {
            for (int i = 0; i < chain.length; i++) {
                X509Certificate certificate = chain[i];
                LOG.debug(i + ": S: " + certificate.getSubjectDN());
                LOG.debug(i + ": I: " + certificate.getIssuerDN());
            }
        }
    }
    try {
        // delegate to default JSSE TrustManager
        defaultTrustManager_.checkServerTrusted(chain, authType);
    } catch (CertificateException ce) {
        LOG.debug("Extended checking of certificate chain");
        // Start with the root and see if the subject or the issuer is
        // in the trustedIssuers HashTable.
        // The root is at the end of the chain.
        boolean trusted = false;
        for (int i = chain.length - 1; i >= 0; i--) {
            X509Certificate cert = chain[i];

            if (isCertificateIssuerTrusted(cert)) {
                LOG.debug("Trusted X509 Issuer: " + cert.getIssuerDN());
                trusted = true;
                break;
            } else if (isCertificateTrusted(cert)) {
                LOG.debug("Trusted X509 Certificate: " + cert.getSubjectDN());
                trusted = true;
                break;
            }
        }

        if (!trusted) {
            LOG.error("No suitable trusted certificate found in truststore: ", ce);
            throw ce;
        }

    }
}

From source file:no.difi.sdp.client.asice.signature.CreateXAdESProperties.java

public Document createPropertiesToSign(List<AsicEAttachable> files, Sertifikat sertifikat) {
    X509Certificate certificate = sertifikat.getX509Certificate();
    byte[] certificateDigestValue = sha1(sertifikat.getEncoded());

    DigestAlgAndValueType certificateDigest = new DigestAlgAndValueType(sha1DigestMethod,
            certificateDigestValue);/*from  ww  w. j a va  2 s.  co m*/
    X509IssuerSerialType certificateIssuer = new X509IssuerSerialType(certificate.getIssuerDN().getName(),
            certificate.getSerialNumber());
    SigningCertificate signingCertificate = new SigningCertificate(
            singletonList(new CertIDType(certificateDigest, certificateIssuer, null)));

    DateTime now = DateTime.now(DateTimeZone.UTC);
    SignedSignatureProperties signedSignatureProperties = new SignedSignatureProperties(now, signingCertificate,
            null, null, null, null);
    SignedDataObjectProperties signedDataObjectProperties = new SignedDataObjectProperties(
            dataObjectFormats(files), null, null, null, null);
    SignedProperties signedProperties = new SignedProperties(signedSignatureProperties,
            signedDataObjectProperties, "SignedProperties");
    QualifyingProperties qualifyingProperties = new QualifyingProperties(signedProperties, null, "#Signature",
            null);

    DOMResult domResult = new DOMResult();
    marshaller.marshal(qualifyingProperties, domResult);
    Document document = (Document) domResult.getNode();

    // Explicitly mark the SignedProperties Id as an Document ID attribute, so that it will be eligble as a reference for signature.
    // If not, it will not be treated as something to sign.
    markAsIdProperty(document, "SignedProperties", "Id");

    return document;
}

From source file:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java

/**
 * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the
 * store with the password using {@link KeyStore#load(InputStream,
 * char[])} method.//  w  w w  .j a  v a  2 s . c  o m
 *
 * @param store The key store holding the certificate details
 * @param alias The alias of the certificate to use
 */
public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    super(store);

    // Loading the CA certificate from store.
    final Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    AsyncHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Embedded SSL certificate has expired.");
    }

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid.");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid.");
            } else {
                Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates.");
                try {
                    for (X509Certificate cert : chain) {
                        Log.i(LOG_TAG, "Server Certificate Details:");
                        Log.i(LOG_TAG, "---------------------------");
                        Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                        Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                        Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                        Log.i(LOG_TAG, "Version: " + cert.getVersion());
                        Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                        Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                        Log.i(LOG_TAG, "---------------------------");

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's public key chain.
                        cert.verify(rootca.getPublicKey());
                    }
                } catch (InvalidKeyException e) {
                    error = e;
                } catch (NoSuchAlgorithmException e) {
                    error = e;
                } catch (NoSuchProviderException e) {
                    error = e;
                } catch (SignatureException e) {
                    error = e;
                }
            }
            if (null != error) {
                Log.e(LOG_TAG, "Certificate error", error);
                throw new CertificateException(error);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return acceptedIssuers;
        }
    } }, null);

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

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

/**
 * Recupera la url para la validacin OCSP del certificado indicado. En el
 * caso de que el certificado sea eDNI el punto OCSP no esta informado, por
 * lo que utilizamos la url prefijada para el eDNI.
 * //  w  ww  .  j a  va  2 s  .  co  m
 * @param certificadoX509
 *            certificado a validar.
 * @return Url
 */
private String getUrlOCSP(X509Certificate certificadoX509) {
    if (certificadoX509.getIssuerDN().getName().contains("OU=DNIE")) {
        if (log.isDebugEnabled())
            log.debug("Es un eDNI, utilizando la url:" + URL_OCSP_EDNI);
        return URL_OCSP_EDNI;
    } else {
        // TODO Implementar extraccin del punto OCSP desde los oids.
        throw new UnsupportedOperationException(
                "TODO implementar la extraccin de puntos de validacin OCSP desde los oids.");
    }
}