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.apache.synapse.transport.nhttp.config.ServerConnFactoryBuilder.java

protected SSLContextDetails createSSLContext(final OMElement keyStoreEl, final OMElement trustStoreEl,
        final OMElement cientAuthEl, final OMElement httpsProtocolsEl,
        final RevocationVerificationManager verificationManager, final String sslProtocol) throws AxisFault {

    KeyManager[] keymanagers = null;
    TrustManager[] trustManagers = null;

    if (keyStoreEl != null) {
        String location = getValueOfElementWithLocalName(keyStoreEl, "Location");
        String type = getValueOfElementWithLocalName(keyStoreEl, "Type");
        String storePassword = getValueOfElementWithLocalName(keyStoreEl, "Password");
        String keyPassword = getValueOfElementWithLocalName(keyStoreEl, "KeyPassword");

        FileInputStream fis = null;
        try {//from w w w . ja  v a2s.  c  om
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.debug(name + " Loading Identity Keystore from : " + location);
            }

            keyStore.load(fis, storePassword.toCharArray());

            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();
            if (log.isInfoEnabled() && keymanagers != null) {
                for (KeyManager keymanager : keymanagers) {
                    if (keymanager instanceof X509KeyManager) {
                        X509KeyManager x509keymanager = (X509KeyManager) keymanager;
                        Enumeration<String> en = keyStore.aliases();
                        while (en.hasMoreElements()) {
                            String s = en.nextElement();
                            X509Certificate[] certs = x509keymanager.getCertificateChain(s);
                            if (certs == null)
                                continue;
                            for (X509Certificate cert : certs) {
                                log.debug(name + " Subject DN: " + cert.getSubjectDN());
                                log.debug(name + " Issuer DN: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }

        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustStoreEl != null) {
        String location = getValueOfElementWithLocalName(trustStoreEl, "Location");
        String type = getValueOfElementWithLocalName(trustStoreEl, "Type");
        String storePassword = getValueOfElementWithLocalName(trustStoreEl, "Password");

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.debug(name + " Loading Trust Keystore from : " + location);
            }

            trustStore.load(fis, storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }
    final String s = cientAuthEl != null ? cientAuthEl.getText() : null;
    final SSLClientAuth clientAuth;
    if ("optional".equalsIgnoreCase(s)) {
        clientAuth = SSLClientAuth.OPTIONAL;
    } else if ("require".equalsIgnoreCase(s)) {
        clientAuth = SSLClientAuth.REQUIRED;
    } else {
        clientAuth = null;
    }

    String[] httpsProtocols = null;
    final String configuredHttpsProtocols = httpsProtocolsEl != null ? httpsProtocolsEl.getText() : null;
    if (configuredHttpsProtocols != null && configuredHttpsProtocols.trim().length() != 0) {
        String[] configuredValues = configuredHttpsProtocols.trim().split(",");
        List<String> protocolList = new ArrayList<String>(configuredValues.length);
        for (String protocol : configuredValues) {
            if (!protocol.trim().isEmpty()) {
                protocolList.add(protocol.trim());
            }
        }

        httpsProtocols = protocolList.toArray(new String[protocolList.size()]);
    }

    try {
        final String sslProtocolValue = sslProtocol != null ? sslProtocol : "TLS";
        SSLContext sslContext = SSLContext.getInstance(sslProtocolValue);
        sslContext.init(keymanagers, trustManagers, null);

        ServerSSLSetupHandler sslSetupHandler = (clientAuth != null || httpsProtocols != null)
                ? new ServerSSLSetupHandler(clientAuth, httpsProtocols, verificationManager)
                : null;

        return new SSLContextDetails(sslContext, sslSetupHandler);
    } catch (GeneralSecurityException gse) {
        log.error(name + " Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}

From source file:de.betterform.connector.http.ssl.BetterFORMKeyStoreManager.java

private X509KeyManager getCustomX509KeyManager(final URL url, final String password)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
        UnrecoverableKeyException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    if (url == null) {
        throw new IllegalArgumentException("BetterFORMKeyStoreManager: Keystore url may not be null");
    }/*  w  w  w .  java2  s . co  m*/

    LOGGER.debug("BetterFORMKeyStoreManager: initializing custom key store");
    KeyStore customKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = null;
    try {
        is = url.openStream();
        customKeystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }

    if (LOGGER.isTraceEnabled()) {
        Enumeration aliases = customKeystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            LOGGER.trace("Trusted certificate '" + alias + "':");
            Certificate trustedcert = customKeystore.getCertificate(alias);
            if (trustedcert != null && trustedcert instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate) trustedcert;
                LOGGER.trace("  Subject DN: " + cert.getSubjectDN());
                LOGGER.trace("  Signature Algorithm: " + cert.getSigAlgName());
                LOGGER.trace("  Valid from: " + cert.getNotBefore());
                LOGGER.trace("  Valid until: " + cert.getNotAfter());
                LOGGER.trace("  Issuer: " + cert.getIssuerDN());
            }
        }
    }
    keyManagerFactory.init(customKeystore, password.toCharArray());

    KeyManager[] customX509KeyManagers = keyManagerFactory.getKeyManagers();
    if (customX509KeyManagers != null && customX509KeyManagers.length > 0) {
        for (int i = 0; i < customX509KeyManagers.length; i++) {
            if (customX509KeyManagers[i] instanceof X509KeyManager) {
                return (X509KeyManager) customX509KeyManagers[i];
            }
        }
    }

    return null;
}

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

/**
 * Metodo encargado de la verificacin de los certificados
 * /*from   w w w  .jav a  2 s . co  m*/
 * @param certificadoX509
 * @throws ExcepcionErrorInterno
 */
public CodigoError validarCRL(X509Certificate certificadoX509) {

    try {
        // 1.- Inicia la factoria de certificados
        CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509",
                BouncyCastleProvider.PROVIDER_NAME);
        log.debug("Validando certificado perteneciente a: " + certificadoX509.getIssuerDN());
        CertPathValidator validador = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);

        // 2.- Configuracin de los parametros del validador
        // 2.1.- Para comprobar que el camino de confianza no esta roto,
        // tengo en cuenta todos los certificados
        PKIXParameters parametros = new PKIXParameters(certificadosConfianza);
        // Fecha para la comprobacin de validez.
        parametros.setDate(new Date());

        if (validacionOnline) {
            // Para la validacin online de del estado de revocacin de los
            // certificados

            // ************
            // creo un almacen( cache ) de certificados y CRLs para no tener
            // que conectarme a las crls
            // en cada validacin

            // Genero un listado de las CRLS que vamos a utilizar para la
            // validacin del certificado.
            List<CRL> listaCRLsCertificadosAlmacenados = new LinkedList<CRL>();

            // Aade las crls de los certificados de confianza reconocidos
            // por Viafirma.
            // estos certificados son los marcados con el prefijo viafirma_
            for (TrustAnchor trustAnchor : certificadosConfianza) {
                // TODO establecer un sistema de cache eficiente
                // TODO recuperar solo las crls del certificado en uso.
                listaCRLsCertificadosAlmacenados
                        .addAll(CRLUtil.getCurrentInstance().getCRLs(trustAnchor.getTrustedCert()));
                // para cada certificado.
            }

            // aado al listado todas las crls del certificado actual. EJ
            // para el caso de
            // un certificado de FNMT el certificado personal contiene CN =
            // CRL1827,OU = FNMT Clase 2 CA,O = FNMT,C = ES
            listaCRLsCertificadosAlmacenados.addAll(CRLUtil.getCurrentInstance().getCRLs(certificadoX509));

            // parametros para la creacin del almacen(cache CRLs)
            CollectionCertStoreParameters params = new CollectionCertStoreParameters(
                    listaCRLsCertificadosAlmacenados);
            CertStore almacen = CertStore.getInstance("Collection", params, BouncyCastleProvider.PROVIDER_NAME);

            parametros.addCertStore(almacen);
        } else {
            // No se utilizan las CRLs para la comprobacin de la
            // revocacin.
            parametros.setRevocationEnabled(false);
        }

        // certificados a validar ( solo 1)
        List<X509Certificate> certificadosValidar = new ArrayList<X509Certificate>(1);
        certificadosValidar.add(certificadoX509);

        // genero el listado de certificados a validar
        CertPath certPath = factoriaCertificados.generateCertPath(certificadosValidar);
        // validacin
        CertPathValidatorResult resultado = validador.validate(certPath, parametros);
        if (log.isDebugEnabled()) {
            if (resultado instanceof java.security.cert.PKIXCertPathValidatorResult) {
                // pintamos el arbol de politicas
                PolicyNode node = ((java.security.cert.PKIXCertPathValidatorResult) resultado).getPolicyTree();
                StringBuffer ruta = new StringBuffer(
                        "Certificado vlido: " + certificadoX509.getSubjectDN().getName());
                while (node != null) {
                    ruta.append("-->");
                    ruta.append(node.getValidPolicy());
                    if (node.getChildren().hasNext()) {
                        node = node.getChildren().next();
                    } else {
                        node = null;
                    }
                }
                log.info("ruta de validacin: " + ruta);
            }
        }
        return CodigoError.OK_CERTIFICADO_VALIDADO;
    } catch (CertificateException e) {
        log.fatal(CodigoError.ERROR_INTERNO, e);
        return CodigoError.ERROR_INTERNO;
    } catch (NoSuchProviderException e) {
        log.fatal(CodigoError.ERROR_INTERNO, e);
        return CodigoError.ERROR_INTERNO;

    } catch (NoSuchAlgorithmException e) {
        log.fatal(CodigoError.ERROR_INTERNO, e);
        return CodigoError.ERROR_INTERNO;
    } catch (InvalidAlgorithmParameterException e) {
        log.fatal(CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO, e);
        return CodigoError.ERROR_VALIDACION_CONFIGURACION_PARAMETRO;
    } catch (CRLException e) {
        log.fatal(CodigoError.ERROR_VALIDACION_CRL, e);
        return CodigoError.ERROR_VALIDACION_CRL;
    } catch (CertPathValidatorException e) {
        // detectamos el tipo de problema
        if (e.getMessage().contains(java.security.cert.CertificateExpiredException.class.getName())
                || e.getMessage().contains("Certificate revocation after")
                || e.getMessage().contains("NotAfter") || e.getMessage().contains("certificate expired on")) {
            log.warn("El certificado esta caducado." + e.getMessage() + " " + certificadoX509.getSubjectDN());
            return CodigoError.ERROR_VALIDACION_CERTIFICADO_CADUCADO;
        } else if (e.getMessage().contains(java.security.SignatureException.class.getName())) {
            log.warn(
                    "Algunos de los certificados en el camino de certificacin no tiene crl. Algunos de los certificados no se puede validar."
                            + e.getMessage() + " " + certificadoX509.getSubjectDN());
            return CodigoError.ERROR_VALIDACION_CRL;
        } else if (e.getMessage().contains("no valid CRL found")) {
            log.warn("No se ha podido comprobar la validez del certificado. " + e.getMessage() + " "
                    + certificadoX509.getSubjectDN());
            return CodigoError.ERROR_VALIDACION_CRL;
        } else if (e.getMessage().contains("CertPath not found")) {
            log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " "
                    + certificadoX509.getIssuerDN());
            return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA;
        } else {
            log.warn("Autoridad de certificacin no reconicida." + e.getMessage() + " "
                    + certificadoX509.getIssuerDN());
            return CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA;
        }

        // TODO java.security.cert.CertPathValidatorException: couldn't
        // validate certificate:
        // java.security.cert.CertificateNotYetValidException: NotBefore:
        // Thu Apr 19 19:22:17 CEST 2007
        // at
        // org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi.engineValidate(PKIXCertPathValidatorSpi.java:819)

    }
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * To get the unique identifier(serialnumber_issuerdn) of the certificate.
 *
 * @param certificate Base64 encoded certificate.
 * @return unique identifier of the certification.
 *//*from w w w.j  a  va  2 s .c  om*/
public String getUniqueIdentifierOfCertificate(String certificate) {
    byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
    ByteArrayInputStream serverCert = new ByteArrayInputStream(cert);
    String uniqueIdentifier = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        while (serverCert.available() > 0) {
            Certificate generatedCertificate = cf.generateCertificate(serverCert);
            X509Certificate x509Certificate = (X509Certificate) generatedCertificate;
            uniqueIdentifier = String
                    .valueOf(x509Certificate.getSerialNumber() + "_" + x509Certificate.getIssuerDN());
            uniqueIdentifier = uniqueIdentifier.replaceAll(",", "#").replaceAll("\"", "'");
        }
    } catch (CertificateException e) {
        log.error("Error while getting serial number of the certificate.", e);
    } finally {
        closeStreams(serverCert);
    }
    return uniqueIdentifier;
}

From source file:org.viafirma.nucleo.firma.imp.FirmaAppletBridgeImp.java

/**
 * Recupera el certificado y el resultado de la firmaenviado por el
 * navegador y lo almacena en el nucleo.
 * /*from   w  w w  .j  av  a 2s  .com*/
 * Proceso:
 * 
 * <pre>
 * 1.- Recupera el XmlSignature desde el parametro message
 * 2.- Desde el XmlSignature recupera el X509Certificado
 * 3.- Desde el xmlSignature envia el xmlSignature completo al nucleo para que este lo persista.
 * 3.- Se lo pasa al ncleo para que lo valide.
 * </pre>
 * 
 * @param request
 * @param response
 * @throws ServletException
 */
private void tratarDatosRecuperados(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");
        String idFirma = request.getParameter(DOCUMENT_TO_SIGN_ID);

        XmlSignUtil xmlSignParser = XmlSignUtil.getInstance();

        // Recuperamos el documento que ha sido firmado
        Document xmlDocument = xmlSignParser.getDocumentFromBase64(xmldoc_b64);

        // Recupero el XMLSignature generado por el cliente
        List<XMLSignature> listXMLSignatureFirmados = xmlSignParser.getXMLSignatureFormDocument(xmlDocument);
        // obtengo el xml signature(resultado de la firma)
        // El usuario solo va ha hacer una firma
        XMLSignature signature = listXMLSignatureFirmados.get(0);

        // recupero el XmlSignature generado por el applet de autenticacin
        X509Certificate certificadoX509 = xmlSignParser.getX509(signature);

        // mostramos el certificado recuperado
        if (log.isDebugEnabled()) {
            log.debug("Firma realizada con el certificado 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);

        // cacheamos el xmlsignature recien obtenido
        nucleo.cachearXmlDocument(sessionID, xmlDocument);

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

}

From source file:com.cordys.coe.util.cgc.ssl.AuthSSLX509TrustManager.java

/**
 * This method checks if the certificate can be trusted. If you do not want to accept the
 * certificate you need to throw an exception.
 *
 * @param   certificates  The certificates to check.
 * @param   sAuthType     The authentication type.
 *
 * @throws  CertificateException  In case the certificate should not be accepted.
 *//*  w  w w  .j  a  va 2s .c o m*/
public void checkClientTrusted(X509Certificate[] certificates, String sAuthType) throws CertificateException {
    if (m_xtmDefault != null) {
        if (certificates != null) {
            for (int c = 0; c < certificates.length; c++) {
                X509Certificate cert = certificates[c];

                if (LOG.isInfoEnabled()) {
                    LOG.info(" Client certificate " + (c + 1) + ":");
                    LOG.info("  Subject DN: " + cert.getSubjectDN());
                    LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
                    LOG.info("  Valid from: " + cert.getNotBefore());
                    LOG.info("  Valid until: " + cert.getNotAfter());
                    LOG.info("  Issuer: " + cert.getIssuerDN());
                }

                try {
                    cert.checkValidity();
                } catch (CertificateExpiredException e) {
                    LOG.fatal("Client certificate " + cert.getSubjectDN() + " is expired.");
                } catch (CertificateNotYetValidException e) {
                    LOG.fatal("Client certificate " + cert.getSubjectDN() + " is not yet valid.");
                }
            }
        }

        // Call the super to do the actual checking.
        m_xtmDefault.checkClientTrusted(certificates, sAuthType);
    }
}

From source file:com.cordys.coe.util.cgc.ssl.AuthSSLX509TrustManager.java

/**
 * This method checks if the server certificate is trusted.
 *
 * @param   certificates  The list of certificates.
 * @param   sAuthType     The authentication type.
 *
 * @throws  CertificateException  DOCUMENTME
 *///  w  w w . ja  v  a 2s  .  c  o m
public void checkServerTrusted(X509Certificate[] certificates, String sAuthType) throws CertificateException {
    if (m_xtmDefault != null) {
        if (certificates != null) {
            for (int c = 0; c < certificates.length; c++) {
                X509Certificate cert = certificates[c];

                if (LOG.isInfoEnabled()) {
                    LOG.info(" Server certificate " + (c + 1) + ":");
                    LOG.info("  Subject DN: " + cert.getSubjectDN());
                    LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
                    LOG.info("  Valid from: " + cert.getNotBefore());
                    LOG.info("  Valid until: " + cert.getNotAfter());
                    LOG.info("  Issuer: " + cert.getIssuerDN());
                }

                try {
                    cert.checkValidity();
                } catch (CertificateExpiredException e) {
                    LOG.fatal("Server certificate " + cert.getSubjectDN() + " is expired.");
                } catch (CertificateNotYetValidException e) {
                    LOG.fatal("Server certificate " + cert.getSubjectDN() + " is not yet valid.");
                }
            }
        }

        // Call the super to do the actual checking.
        m_xtmDefault.checkServerTrusted(certificates, sAuthType);
    }
}

From source file:org.apache.cloudstack.network.lb.CertServiceImpl.java

private void validateChain(List<Certificate> chain, Certificate cert) {

    List<Certificate> certs = new ArrayList<Certificate>();
    Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);/*from www  .j  a  va  2  s  . c  o  m*/

    for (Certificate c : certs) {
        if (!(c instanceof X509Certificate))
            throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");

        X509Certificate xCert = (X509Certificate) c;

        Principal subject = xCert.getSubjectDN();
        Principal issuer = xCert.getIssuerDN();

        anchors.add(new TrustAnchor(xCert, null));
    }

    X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);

    PKIXBuilderParameters params = null;
    try {
        params = new PKIXBuilderParameters(anchors, target);
        params.setRevocationEnabled(false);
        params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
        builder.build(params);

    } catch (InvalidAlgorithmParameterException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (CertPathBuilderException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchProviderException e) {
        throw new CloudRuntimeException("No provider for certificate validation", e);
    }

}

From source file:org.ejbca.extra.caservice.ExtRACAServiceWorker.java

/**
 * Method used to retrieve which administrator to use.
 * If message is signed then use the signer as admin otherwise use InternalUser
 * @throws SignatureException /*ww w .j a v  a 2  s.  c o  m*/
 * @throws AuthorizationDeniedException 
 */
private Admin getAdmin(SubMessages submessages) throws SignatureException, AuthorizationDeniedException {
    if (submessages.isSigned()) {
        // Check if Signer Cert is revoked
        X509Certificate signerCert = submessages.getSignerCert();
        Admin admin = userAdminSession.getAdmin(signerCert);
        // Check that user have the administrator flag set.
        userAdminSession.checkIfCertificateBelongToUser(admin, signerCert.getSerialNumber(),
                signerCert.getIssuerDN().toString());
        boolean isRevoked = certificateStoreSession.isRevoked(
                CertTools.stringToBCDNString(signerCert.getIssuerDN().toString()),
                signerCert.getSerialNumber());
        if (isRevoked) {
            throw new SignatureException("Error Signer certificate doesn't exist or is revoked.");
        }
        return admin;
    }
    return internalUser;
}

From source file:com.fine47.http.SecureSocketFactory.java

private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException,
        NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(store);

    // Loading the CA certificate from store.
    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);
    ActivityHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Found expired SSL certificate in this store: " + factoryId);
    }/*from  w w  w  . j  a  va  2  s  . co  m*/

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

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

    // Get the public key.
    publicKey = rootca.getPublicKey();

    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
                try {
                    for (X509Certificate cert : chain) {
                        if (ActivityHttpClient.isDebugging()) {
                            Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:");
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                            Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                            Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                        }

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

                        // Verify the certificate's chain.
                        cert.verify(publicKey);
                    }
                } catch (InvalidKeyException ex) {
                    error = ex;
                } catch (NoSuchAlgorithmException ex) {
                    error = ex;
                } catch (NoSuchProviderException ex) {
                    error = ex;
                } catch (SignatureException ex) {
                    error = ex;
                }
            if (null != error && ActivityHttpClient.isDebugging()) {
                Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error);
                throw new CertificateException(error);
            }
        }

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

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}