DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more

How to Fix the ''Not a Trusted Site'' Error on Your Client Application

Need help resolving the ''Not a trusted site'' error on your application? Check out this tutorial to learn how to establish an SSL-based connection to a remote server.

Abhijit Pritam Dutta user avatar by
Abhijit Pritam Dutta
CORE ·
Aug. 31, 18 · Tutorial
Like (3)
Save
Tweet
Share
7.13K Views

Join the DZone community and get the full member experience.

Join For Free

Most of us have frequently encountered an issue when our client application tries to establish an SSL-based connection to a remote server, sending out one of the common errors, “Not a trusted site,” "This Connection is Untrusted," or "The site's security certificate is not trusted." This warning is raised by your client application and refused to connect to the remote server. This is one of the most common issues we, web service developers, face in our day-to-day work. The main reason is that the certificate provided by the server application for an SSL handshake is not registered in your truststore file. How will you resolve this issue? You have to download the remote server certificate and import it into your trust store. Here, I am providing an example of a Java application that was originally provided by Sun Microsystems that I have customized for this demonstration. Let's get into it!  

First, let's discuss this application and how to configure it to download a server certificate and add it into your truststore to avoid this issue. 

First, you need to change the following lines of code as per your requirements:

String newTrustStore = "C:\\customkeystore\\yournewtruststore.jks"; // your truststore

char[] passphrase = "truststore_Password".toCharArray(); // your truststore password

String keystore = "C:\\customkeystore\\yourkestore";// this is the keystore to connect to the remote server

String keystorepass = "keystore_password";// This is the keystore password 


In the last two lines, normally, you will provide the location of the key store, and its password is provided by your remote server owner to connect to their service through SSL based connection. 

Now, the following two lines of code will be required to modify as per your application configuration: 

KeyStore clientStore = KeyStore.getInstance("PKCS12");// or jks

KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");// or IBMX503 


Now, you will need to change the line below with your remote server URL: 

String httpsurl = "https://your.remote.server.net"; 


Now, for the proxy setting, if your application connects through a proxy server, go ahead and change the following code with your proxy setting:

 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.hedani.net", 8090));  


If you don’t have any proxy setting, just comment out above the line and uncomment below the line of code in the following Java application:

//Proxy proxy = null; 


Finally, modify the line of code below:

String alias = "alies_to_new_certificate_in_trust_store"; 


This is the alias to the certificate that will be added from the remove server to your truststore. 

Now, compile and execute the code below to the modified application, which will add the server certificate into your truststore and fix this issue. 

Hope this article will help you with your next project!

/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */



import java.io.*;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;

import java.security.*;
import java.security.cert.*;
import java.security.cert.Certificate;

import javax.net.ssl.*;


public class GenerateTrustStore {


    public static void main(String[] args) throws Exception {
    SSLContext sslContext = null;
    KeyManager[] kms = null;
    String newTrustStore = "C:\\customkeystore\\my_trust_store.jks";
    char[] passphrase = "trust_store_password".toCharArray();
    String keystore = "C:\\customkeystore\\remote_server_keystore.jks";
String keystorepass = "remote_server_keystore_password";
try{
KeyStore clientStore = KeyStore.getInstance("JKS");// keystore type
    clientStore.load(new FileInputStream(keystore), keystorepass.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(clientStore, keystorepass.toCharArray());
    kms = kmf.getKeyManagers();
    sslContext = SSLContext.getInstance("TLS");
}catch(Exception e){
e.printStackTrace(System.out);
}
String httpsurl = "https://remote_server_url.net";
    URL url;
try {
url = new URL(null , httpsurl, new sun.net.www.protocol.https.Handler());
} catch (MalformedURLException e1) {
System.out.println("MalformedURLException occurred " + e1.getMessage());
throw new Exception();
}
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(newTrustStore), passphrase);  
    TrustManager[] trustAllCerts = new TrustManager[] {
       new X509TrustManager() {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
          }

          public void checkClientTrusted(X509Certificate[] certs, String authType) {  }

          public void checkServerTrusted(X509Certificate[] certs, String authType) {  }

       }
    }; 

    HostnameVerifier hv = new HostnameVerifier()
    {
        public boolean verify(String urlHostName, SSLSession session)
        {
            System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                    + session.getPeerHost());
            return true;
        }
    };

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    sslContext.init(kms, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.mydomain.net", 8090));    
    //if No proxy, use below line of code and comment out above line
    //Proxy proxy = null;


    HttpsURLConnection conn = null;
conn = (proxy != null) ? (HttpsURLConnection) url.openConnection(proxy) : (HttpsURLConnection) url.openConnection();
try{
System.out.println("Connecting to server and receiving server certificats...");
conn.connect();
}catch(Exception e){
e.printStackTrace(System.out);
}

BufferedReader reader =
        new BufferedReader(new InputStreamReader(System.in));

    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    Certificate[] certs = conn.getServerCertificates();
    for(int i =0; i< certs.length; i++){
    X509Certificate cert = ( (X509Certificate) certs[i]);
        System.out.println
            (" " + (i + 1) + " Subject " + cert.getSubjectDN());
        System.out.println("   Issuer  " + cert.getIssuerDN());
        sha1.update(cert.getEncoded());
        System.out.println("   sha1    " + toHexString(sha1.digest()));
        md5.update(cert.getEncoded());
        System.out.println("   md5     " + toHexString(md5.digest()));
        System.out.println();
    }

    System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
    String line = reader.readLine().trim();
    int k;
    try {
        k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
    } catch (NumberFormatException e) {
        System.out.println("KeyStore not changed");
        return;
    }

    String alias = "alies_to_new_certificate_in_trust_store";

    X509Certificate cert = ( (X509Certificate) certs[k]);    
    ks.setCertificateEntry(alias, cert);

    OutputStream out = new FileOutputStream(newTrustStore);
    ks.store(out, passphrase);
    out.close();

    System.out.println();
    System.out.println(cert);
    System.out.println();
    System.out.println
        ("Added certificate to keystore '"+ newTrustStore + "' using alias '"
        + alias + "'");
    conn.disconnect();
    }

    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

    private static String toHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 3);
    for (int b : bytes) {
        b &= 0xff;
        sb.append(HEXDIGITS[b >> 4]);
        sb.append(HEXDIGITS[b & 15]);
        sb.append(' ');
    }
    return sb.toString();
    }
}
application

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Custom Validators in Quarkus
  • Frontend Troubleshooting Using OpenTelemetry
  • What’s New in Flutter 3.7?
  • 5 Steps for Getting Started in Deep Learning

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: