17

I am new to this SSL and X509Certificate Concepts. What all I need is, Is there any way to get the Certificate Information from a given Url

For Example: If User has typed https://www.google.com then I need the Certificate Information for that Programmatically.

Edit:

Finally, I got the Certificate Information from Server.

Now, my questions are:

1. How can I Check Certificate is Trusted or not ?

2. How can I add the Certificate to the Trust Manager ?

3. Even, if it is Un-trusted Certificate, if the user wants to continue with that then i need to add the certificate to the Trust Manager. How can i Achieve this?

4. Is it that, inorder to check a Certificate is trusted or not, do we really need to have another certificate to compare ?

I am very much new to these X.509 Certificate.

Any help will be really Appreciated.

EDIT:

This is what i have Tried. But, none of them is Helping me. I need to get the Certificate is trusted or not.

X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                    for (TrustManager tm : managers) {
                        if (tm instanceof X509TrustManager) {
                            ((X509TrustManager) tm).checkClientTrusted(
                                    chain, authType);
                        }
                    }
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) {

                    for (X509Certificate cert : chain) {

                        final String mCertificatinoType = cert.getType();
                        Date afterDate = cert.getNotAfter();
                        Date beforeDate = cert.getNotBefore();
                        Date currentDate = new Date();

                        try {
                            cert.checkValidity(new Date());
                        } catch (CertificateExpiredException e) {
                            LoginActivity.isExpired = true;
                            e.printStackTrace();
                        } catch (CertificateNotYetValidException e) {
                            LoginActivity.isInValid = true;
                            e.printStackTrace();
                        }

                        try {
                            cert.verify(trustedRoot.getPublicKey());
                        } catch (InvalidKeyException e) {
                            e.printStackTrace();
                        } catch (CertificateException e) {
                            e.printStackTrace();
                        } catch (NoSuchAlgorithmException e) {
                            e.printStackTrace();
                        } catch (NoSuchProviderException e) {
                            e.printStackTrace();
                        } catch (SignatureException e) {
                            e.printStackTrace();
                        }

                        try {
                            if (cert.getIssuerX500Principal().equals(
                                    trustedRoot.getIssuerX500Principal())) {

                            }
                            cert.verify(trustedHost.getPublicKey());
                        } catch (InvalidKeyException e) {
                            e.printStackTrace();
                        } catch (CertificateException e) {
                            e.printStackTrace();
                        } catch (NoSuchAlgorithmException e) {
                            e.printStackTrace();
                        } catch (NoSuchProviderException e) {
                            e.printStackTrace();
                        } catch (SignatureException e) {
                            e.printStackTrace();
                        }

                        if (afterDate.compareTo(currentDate)
                                * currentDate.compareTo(beforeDate) > 0) {
                        } else {

                        }

                        if (cert.getIssuerX500Principal().equals(
                                trustedRoot.getIssuerX500Principal())) {
                            return;
                        }
                    }

                    // for (X509Certificate cert : chain) {
                    // URL url;
                    // String host = "";
                    // if (baseHostString.equalsIgnoreCase("")) {
                    // final Settings settings = mApplication
                    // .getSettings();
                    // try {
                    // url = new URL(
                    // settings.serverAddress.toString());
                    // host = url.getAuthority();
                    // } catch (MalformedURLException e) {
                    // e.printStackTrace();
                    // }
                    // } else {
                    //
                    // }
                    //
                    // String dn = cert.getSubjectDN().getName();
                    // String CN = getValByAttributeTypeFromIssuerDN(dn,
                    // "CN=");
                    // if (CN.equalsIgnoreCase(host)) {
                    // if (cert.getIssuerX500Principal().equals(
                    // trustedRoot.getIssuerX500Principal())) {
                    // return;
                    // } else {
                    // }
                    // } else {
                    // }
                    // }
                    for (TrustManager tm : managers) {
                        if (tm instanceof X509TrustManager) {
                            try {
                                ((X509TrustManager) tm).checkServerTrusted(
                                        chain, authType);
                            } catch (CertificateException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    ArrayList<X509Certificate> issuers = new ArrayList<>();
                    for (TrustManager tm : managers) {
                        if (tm instanceof X509TrustManager) {
                            issuers.addAll(Arrays
                                    .asList(((X509TrustManager) tm)
                                            .getAcceptedIssuers()));
                        }
                    }
                    return issuers.toArray(new X509Certificate[issuers
                            .size()]);
                }

            };
Manu
  • 4,730
  • 2
  • 20
  • 45
  • Possible duplicate of [Using openssl to get the certificate from a server](http://stackoverflow.com/questions/7885785/using-openssl-to-get-the-certificate-from-a-server) – jww May 12 '15 at 15:54
  • Do you want to do it with Android Java, or with OpenSSL? And what do you want to do after you get the certificate? – jww May 12 '15 at 16:15
  • With Android Java... I need to add that certificate to the trust Manager.. and Should allow that untrusted server certificate too @jww. The link you shared is different – Manu May 13 '15 at 05:02
  • @jww this is not a duplicate of that. – EpicPandaForce May 13 '15 at 09:03
  • @EpicPandaForce: Is there any way to check X509 Certificate is trusted or not ? – Manu May 13 '15 at 09:06
  • unfortunately, it's a bit messy and a tough problem - it's akin to http://stackoverflow.com/a/30085361/2413303 (you need to initialize the SSL Context and define your own Trust Manager, and you also need to actually **check** the certificate as per http://stackoverflow.com/a/8694377/2413303 but I'm trying to find data and I can't seem to find a **proper implementation** of the trust manager. I should just find the code made by the Java devs...) – EpicPandaForce May 13 '15 at 09:09
  • This looks relevant: https://jcalcote.wordpress.com/2010/06/22/managing-a-dynamic-java-trust-store/ – EpicPandaForce May 13 '15 at 09:10
  • @EpicPandaForce: Hi, how can i get keystore for particular certificate. In the abouve link you shared. ReloadableX509TrustManager(String tspath). what is this tsPath ? Could you please help me please – Manu May 13 '15 at 09:31
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/77698/discussion-between-manohar-perepa-and-epicpandaforce). – Manu May 13 '15 at 09:56
  • If you don't have a "truststore" `KeyStore`, then to load the default, you need to use ` TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());` and `trustManagerFactory.init((KeyStore)null);`, this initializes the trust manager factory with the default trust managers. – EpicPandaForce May 13 '15 at 10:13

1 Answers1

6

Finally, cracked!

                X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                    for (TrustManager tm : managers) {
                        if (tm instanceof X509TrustManager) {
                            ((X509TrustManager) tm).checkClientTrusted(
                                    chain, authType);
                        }
                    }
                }

                @Override
                public void checkServerTrusted(
                        final X509Certificate[] chain, String authType) {

                    for (X509Certificate cert : chain) {

                        final String mCertificatinoType = cert.getType();
                        Date afterDate = cert.getNotAfter();
                        Date beforeDate = cert.getNotBefore();
                        Date currentDate = new Date();

                        try {
                            cert.checkValidity(new Date());
                        } catch (CertificateExpiredException e) {
                            isExpired = true;
                            e.printStackTrace();
                        } catch (CertificateNotYetValidException e) {
                            isInValid = true;
                            e.printStackTrace();
                        }

                        if (afterDate.compareTo(currentDate)
                                * currentDate.compareTo(beforeDate) > 0) {
                            isExpired = false;
                        } else {
                            isExpired = true;
                        }

                        String dn = cert.getSubjectDN().getName();
                        String CN = getValByAttributeTypeFromIssuerDN(dn,
                                "CN=");

                        String host = "";
                        if (TextUtils.isEmpty(query)) {
                            if (baseHostString.equalsIgnoreCase("")) {
                                final Settings settings = mApplication
                                        .getSettings();
                                try {
                                    URL url = new URL(
                                            settings.serverAddress
                                                    .toString());
                                    host = url.getAuthority();
                                    if (host.contains(String.valueOf(url
                                            .getPort()))) {
                                        String toBeReplaced = ":"
                                                + url.getPort();
                                        host = host.replace(toBeReplaced,
                                                "");
                                    }
                                } catch (MalformedURLException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                try {
                                    URL url = new URL(baseHostString);
                                    host = url.getAuthority();
                                    if (host.contains(String.valueOf(url
                                            .getPort()))) {
                                        String toBeReplaced = ":"
                                                + url.getPort();
                                        host = host.replace(toBeReplaced,
                                                "");
                                    }
                                } catch (MalformedURLException e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            try {
                                URL url = new URL(query);
                                host = url.getAuthority();
                                if (host.contains(String.valueOf(url
                                        .getPort()))) {
                                    String toBeReplaced = ":"
                                            + url.getPort();
                                    host = host.replace(toBeReplaced, "");
                                }
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            }
                        }

                        if (CN.equalsIgnoreCase(host)) {
                            isHostMisMatch = false;
                        } else {
                            isHostMisMatch = true;
                        }

                        for (TrustManager tm : managers) {
                            if (tm instanceof X509TrustManager) {
                                try {
                                    ((X509TrustManager) tm)
                                            .checkServerTrusted(chain,
                                                    authType);
                                } catch (CertificateException e) {
                                    if (e.getMessage() != null
                                            && e.getMessage()
                                                    .contains(
                                                            "Trust anchor for certification path not found.")) {
                                        isNotTrusted = true;
                                        mApplication
                                                .setCurrentCertificate(chain);
                                    }
                                    e.printStackTrace();
                                }
                            }
                        }

                        if (cert.getIssuerX500Principal().equals(
                                trustedRoot.getIssuerX500Principal())) {
                            return;
                        }
                    }

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    ArrayList<X509Certificate> issuers = new ArrayList<>();
                    for (TrustManager tm : managers) {
                        if (tm instanceof X509TrustManager) {
                            issuers.addAll(Arrays
                                    .asList(((X509TrustManager) tm)
                                            .getAcceptedIssuers()));
                        }
                    }
                    return issuers.toArray(new X509Certificate[issuers
                            .size()]);
                }

            };

Thanks Everybody.

Manu
  • 4,730
  • 2
  • 20
  • 45