banner



How To Configure Tls For Java Soap Service

This is a Java, SSL-based client which facilitates both RESTFul and SOAP spider web service calls to different servers. To better empathize the topic at hand, you lot should also have cognition of the beneath-mentioned topics:

  • What is an SSL certificate?
  • What is an SSL handshake?
  • What is a Coffee Key Shop (JKS)?
  • What is a Java Trust Store (JTS)?
  • What is a PKCS document/primal store?
  • What is HTTPS network protocol?

This is going to be a complete SSL-based client application for both RESTFul and Lather calls. The beauty of this project is that information technology supports both JKS and PKCS certificates through different configuration facilities provided with this project. Yous can download the project and just demand to refractor this framework/codebase and replace the existing Java classes with your classes to make this framework fulfill your business needs. You can download the project from here.

Nosotros are going to develop this small projection in Eclipse. Let's go over, stride-past-step, how to create the client awarding.

1. Create a simple Java project, like below:

Image title

Give the project the name SSLClient, like below:

Image title

Click 'Terminate' to create the project.

Now, right-click on source folder,src,and add a new package, com.bhaiti.kela.common.config, and add a new form, ApplicationConfig, to it.

Offset, add a new parcel: New->package

Image title

At present to add the form to it, click on the package and from the menu and select New->class.

Image title

Copy and paste the below code into this form. This is our config class where we will store all the config data for this application.

          bundle com.bhaiti.kela.common.config;  public last course ApplicationConfig {  private String KEYSTOREPATH = null; private Cord TRUSTSTOREPATH = null; private Cord KEYSTOREPW = nada; individual Cord TRUSTSTOREPW = cipher; private String KEYPASS = aught; private Cord HTTPS_SERV_URL = null; private String trustAllCertificate = "fake";// DEFAULT VALUE individual String keystoreType = "JKS";// DEFAULT VALUE individual String regex = null; individual String keymanageralgorithm = cypher; private int mqreadinterval = 1; individual int httpsfialureinterval = 5; private int prodissueinterval = 1;  individual static ApplicationConfig myinstance = null;  public static ApplicationConfig getInstance() { System.out.println("in ApplicationConfig getInstance"); if (myinstance == null) { myinstance = new ApplicationConfig(); } return myinstance; }  private ApplicationConfig() {  }  public String getKEYSTOREPATH() { render KEYSTOREPATH; }  public void setKEYSTOREPATH(Cord kEYSTOREPATH) { KEYSTOREPATH = kEYSTOREPATH; }  public String getTRUSTSTOREPATH() { render TRUSTSTOREPATH; }  public void setTRUSTSTOREPATH(String tRUSTSTOREPATH) { TRUSTSTOREPATH = tRUSTSTOREPATH; }  public String getKEYSTOREPW() { return KEYSTOREPW; }  public void setKEYSTOREPW(String kEYSTOREPW) { KEYSTOREPW = kEYSTOREPW; }  public String getTRUSTSTOREPW() { return TRUSTSTOREPW; }  public void setTRUSTSTOREPW(String tRUSTSTOREPW) { TRUSTSTOREPW = tRUSTSTOREPW; }  public String getKEYPASS() { return KEYPASS; }  public void setKEYPASS(Cord kEYPASS) { KEYPASS = kEYPASS; }  public String getHTTPS_SERV_URL() { return HTTPS_SERV_URL; }  public void setHTTPS_SERV_URL(Cord hTTPS_SERV_URL) { HTTPS_SERV_URL = hTTPS_SERV_URL; }  public String getTrustAllCertificate() { return trustAllCertificate; }  public void setTrustAllCertificate(String trustAllCertificate) { this.trustAllCertificate = trustAllCertificate; }  public String getKeystoreType() { render keystoreType; }  public void setKeystoreType(String keystoreType) { this.keystoreType = keystoreType; }  public String getKeymanageralgorithm() { return keymanageralgorithm; }  public void setKeymanageralgorithm(String keymanageralgorithm) { this.keymanageralgorithm = keymanageralgorithm; }  public int getMqreadinterval() { return mqreadinterval; }  public void setMqreadinterval(int mqreadinterval) { this.mqreadinterval = mqreadinterval; }  public int getHttpsfialureinterval() { render httpsfialureinterval; }  public void setHttpsfialureinterval(int httpsfialureinterval) { this.httpsfialureinterval = httpsfialureinterval; }  public int getProdissueinterval() { render prodissueinterval; }  public void setProdissueinterval(int prodissueinterval) { this.prodissueinterval = prodissueinterval; }  public void setREGEX(String regex) { this.regex = regex; }  public String getREGEX() { render this.regex; }  public static ApplicationConfig getMyinstance() { return myinstance; }  public static void setMyinstance(ApplicationConfig myinstance) { ApplicationConfig.myinstance = myinstance; } }                  

Now we are going to add a new class call SSLContextConfig this class will initialize the truststore, keystore and certificate particular to connect to the remove server through a SSL based HTTPS connection. Hither based on trust store, key store and document particular the below class will create an object of type SSLContext and returns it to caller for establish an SSL based HTTPS connection. Beauty of this form is that I accept design it in such a style that your can use both jks and pkcs certificate and that also can exist configurable through system.properties file.

Add package com.bhaiti.kela.ssl.config and add below grade

          package com.bhaiti.kela.ssl.config;   import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import coffee.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import coffee.security.cert.CertificateException;  import javax.internet.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.cyberspace.ssl.TrustManagerFactory;  import javax.net.ssl.TrustManager; import javax.internet.ssl.X509TrustManager; import java.security.cert.X509Certificate;  import org.apache.log4j.Logger; import com.bhaiti.kela.mutual.config.ApplicationConfig; import javax.net.ssl.KeyManager;    public class SSLContextConfig {   individual static terminal Logger LOGGER = Logger.getLogger(SSLContextConfig.class); private ApplicationConfig config_ = ApplicationConfig.getInstance(); private TrustManager[] trustAllCerts = naught; individual Cord keymanageralgorithm = null; public SSLContext setupSslContext(){  SSLContext sslContext = null; boolean trustall = false; try {  String keyStorePath = config_.getKEYSTOREPATH(); String trustStorePath = config_.getTRUSTSTOREPATH(); String keyStorePw = config_.getKEYSTOREPW(); String trustStorePw = config_.getTRUSTSTOREPW(); Cord keyPass = config_.getKEYPASS(); String trustAllCertificate = config_.getTrustAllCertificate(); Cord keystoreType = config_.getKeystoreType(); keymanageralgorithm = config_.getKeymanageralgorithm(); trustAllCerts = new TrustManager[] {        new X509TrustManager() {           public java.security.cert.X509Certificate[] getAcceptedIssuers() {             return nothing;           }            public void checkClientTrusted(X509Certificate[] certs, String authType) {  }            public void checkServerTrusted(X509Certificate[] certs, Cord authType) {  }         }     }; if(trustAllCertificate.equalsIgnoreCase("True")){ trustall = true; } if (keystoreType.equalsIgnoreCase("JKS")) sslContext = initializeSSLContext(keyStorePath, keyStorePw, trustStorePath, trustStorePw, keyPass,trustall); else sslContext = initializeSSLContextP12Cert(keyStorePath, keyStorePw, trustStorePath, trustStorePw, keyPass,trustall);  }  catch (Exception exp) { LOGGER.error("ConfigException exception occurred while reading the config file : " +exp.getMessage()); exp.printStackTrace(); }  render sslContext; }  /**  *   * @param keyStorePath  * @param pwKeyStore  * @param trustStorePath  * @param pwTrustStore  * @param keyPass  * @return  * @throws Exception  */ individual SSLContext initializeSSLContext(terminal String keyStorePath, final String pwKeyStore, final String trustStorePath, final String pwTrustStore, concluding String keyPass, final boolean trustall) { LOGGER.info(" In initializeSSLContext"); char[] keyStorePw = pwKeyStore.toCharArray(); char[] trustStorePw = pwTrustStore.toCharArray(); char[] keyPw = keyPass.toCharArray(); SecureRandom secureRandom = new SecureRandom(); secureRandom.nextInt();  KeyStore ks = zero; try { ks = KeyStore.getInstance("JKS"); } grab (KeyStoreException exp) { LOGGER.mistake("KeyStoreException exception occurred while reading the config file : " +exp.getMessage()); } FileInputStream fis = goose egg; try { try { fis = new FileInputStream(keyStorePath); } catch (FileNotFoundException exp) { LOGGER.error("FileNotFoundException exception occurred " +exp.getMessage()); } try { ks.load(fis, keyStorePw); } grab (NoSuchAlgorithmException exp) { LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage()); } catch (CertificateException exp) { LOGGER.mistake("CertificateException exception occurred " +exp.getMessage()); } take hold of (IOException exp) { LOGGER.mistake("CertificateException exception occurred " +exp.getMessage()); } } finally { if (fis != nothing) try { fis.close(); } take hold of (IOException exp) { LOGGER.error("IOException exception occurred " +exp.getMessage()); } }  LOGGER.info("[initializeSSLContext] KMF keystorepw loaded.");  KeyManagerFactory kmf = nada; try { kmf = KeyManagerFactory.getInstance(keymanageralgorithm); } catch (NoSuchAlgorithmException exp) { LOGGER.fault("IOException exception occurred " +exp.getMessage()); } try { kmf.init(ks, keyPw); } take hold of (UnrecoverableKeyException exp) { LOGGER.fault("UnrecoverableKeyException exception occurred " +exp.getMessage()); } take hold of (KeyStoreException exp) { LOGGER.fault("KeyStoreException exception occurred " +exp.getMessage()); } catch (NoSuchAlgorithmException exp) { LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage()); }  LOGGER.info("[initializeSSLContext] KMF init done.");  KeyStore ts = null; try { ts = KeyStore.getInstance("JKS"); } catch (KeyStoreException exp) { LOGGER.fault("NoSuchAlgorithmException exception occurred " +exp.getMessage()); } FileInputStream tfis = null; SSLContext sslContext = null; try { tfis = new FileInputStream(trustStorePath); ts.load(tfis, trustStorePw); TrustManagerFactory tmf = TrustManagerFactory.getInstance(keymanageralgorithm); tmf.init(ts); LOGGER.info("[initializeSSLContext] Truststore initialized"); sslContext = SSLContext.getInstance("TLS");  if(trustall) sslContext.init(kmf.getKeyManagers(), trustAllCerts,secureRandom); else sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers() ,secureRandom);  } catch (NoSuchAlgorithmException exp) { LOGGER.mistake("NoSuchAlgorithmException exception occurred " +exp.getMessage()); } catch (CertificateException exp) { LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage()); } catch (IOException exp) { LOGGER.mistake("NoSuchAlgorithmException exception occurred " +exp.getMessage()); } catch (KeyStoreException exp) { LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage()); } catch (KeyManagementException exp) { LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage()); } finally { if (tfis != null) try { tfis.close(); } catch (IOException exp) { LOGGER.fault("NoSuchAlgorithmException exception occurred " +exp.getMessage()); } }  if((sslContext == null)){ LOGGER.mistake("[initializeSSLContext] sslContext is null"); System.exit(-i); } return sslContext; }  /**  *   * @param keyStorePath  * @param pwKeyStore  * @param trustStorePath  * @param pwTrustStore  * @param keyPass  * @return  * @throws Exception  */ private SSLContext initializeSSLContextP12Cert(final Cord keyStorePath, final String pwKeyStore, final String trustStorePath, last String pwTrustStore, final String keyPass,final boolean trustall) { LOGGER.info("In initializeSSLContextP12Cert"); SSLContext sslContext = null;     String keystore = keyStorePath;     String keystorepass = pwKeyStore;     String truststore = trustStorePath;     String truststorepass = pwTrustStore;      endeavor{     KeyStore clientStore = KeyStore.getInstance("PKCS12");         clientStore.load(new FileInputStream(keystore), keystorepass.toCharArray());          KeyManagerFactory kmf = KeyManagerFactory.getInstance(keymanageralgorithm);         kmf.init(clientStore, keystorepass.toCharArray());         KeyManager[] kms = kmf.getKeyManagers();          KeyStore trustStore = KeyStore.getInstance("JKS");         trustStore.load(new FileInputStream(truststore), truststorepass.toCharArray());          TrustManagerFactory tmf = TrustManagerFactory.getInstance(keymanageralgorithm);         tmf.init(trustStore);         TrustManager[] tms = tmf.getTrustManagers();         sslContext = SSLContext.getInstance("TLS");          if(trustall)         sslContext.init(kms, trustAllCerts, new SecureRandom());         else         sslContext.init(kms, tms, new SecureRandom());      } catch (NoSuchAlgorithmException exp) { LOGGER.error("NoSuchAlgorithmException exception occurred " +exp.getMessage()); } take hold of (CertificateException exp) { LOGGER.fault("CertificateException exception occurred " +exp.getMessage()); } grab (IOException exp) { LOGGER.mistake("IOException occurred while reading the primal file  " +exp.getMessage()); } catch (KeyStoreException exp) { LOGGER.error("KeyStoreException exception occurred " +exp.getMessage()); } catch (KeyManagementException exp) { LOGGER.fault("KeyManagementException exception occurred " +exp.getMessage()); }catch (UnrecoverableKeyException exp) { LOGGER.error("UnrecoverableKeyException exception occurred " +exp.getMessage()); }      if((sslContext == null)){ LOGGER.fault("[initializeSSLContext] sslContext is cypher"); LOGGER.error("[initializeSSLContext] verify ssl config"); LOGGER.error("MyREST application exit with status code -1"); //Arrangement.go out(-1); }     LOGGER.info("[initializeSSLContextP12Cert] Truststore and KeyStore initialized"); return sslContext;   }   }        

At present nosotros need to add the two config files beneath to the root directory of this projection. The first one is holding all the config information for this project (please read the certificate configuration part advisedly) and the second file is a log belongings file. Please go along in mind that the below files are just sample files only, so do non blindly copy them to your project. Create the below 2 files in your project as per your config data.

          LOG_PROPERTY_FILE_PATH=C:\\Projects\\SSLClient\\log.properties KEYSTOREPATH=C:\\Projects\\SSLClient\\key\\etc\\mykestore.jks TRUSTSTOREPATH=kelabhalkoikoribi KEYSTOREPW=kelapitonpabi TRUSTSTOREPW=kelabhalkoikoribi KEYPASS=kelapitonpabi keystoreType=jks ;assign to a higher place fundamental as 'keystoreType=p12' if y'all are using a PKCS certificate/store trustAllCertificate=aye ; assign 'no' if you don't want your application to forcefulness whether a site should be trusted or not, if you are getting a fault like not a trusted site you lot can ;put the value as 'no' to avoid such upshot. But not recomented. keymanageralgorithm=SunX509 // For IBM it should be IbmX509        
          log4j.rootLogger=INFO, file, stdout  # Direct log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=C:\\Projects\\SSLClient\\log\\sslClient.log log4j.appender.file.MaxFileSize=10MB log4j.appender.file.MaxBackupIndex=10 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{ane}:%L - %one thousand%n  # Directly log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=Arrangement.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %thousand%n        

At present add a new packet, com.bhaiti.kela.ssl.client, and add together the below class to information technology. This is our bodily customer application class from which nosotros volition brand all the SSL-based HTTPS calls.

          package com.bhaiti.kela.ssl.customer;  import java.io.InputStreamReader; import coffee.io.OutputStreamWriter; import java.internet.URL; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext;  import org.apache.log4j.Logger;  import com.bhaiti.kela.common.config.ApplicationConfig; import com.bhaiti.kela.ssl.config.SSLContextConfig;  public class SSLClient {  static SSLClient _sslClient = nix; int _responseCode = -ane; static private ApplicationConfig config_ = ApplicationConfig.getInstance(); private static last Logger LOGGER = Logger.getLogger(SSLClient.grade); URL url_ = nix; HttpsURLConnection connection_ = nada; static SSLContext sslContext = null;  private SSLClient() { SSLContextConfig sslconfig = new SSLContextConfig(); sslContext = sslconfig.setupSslContext(); }  public static SSLClient getSSLClient() {  if (_sslClient == zero) { _sslClient = new SSLClient(); } return _sslClient; }  individual boolean setSSLConnection(URL url, String method, String msgtype) { HttpsURLConnection.setDefaultSSLSocketFactory(sslContext .getSocketFactory()); endeavor { connection_ = (HttpsURLConnection) url.openConnection(); connection_.setSSLSocketFactory(sslContext.getSocketFactory()); if(method == "POST") connection_.setRequestMethod(method); connection_.setDoOutput(true ); connection_.setRequestProperty("Content-Type", msgtype /*"text/xml" */ ); connection_.connect(); return true; } catch (Exception due east) { LOGGER.error("Exception occurred while establishing connexion to SSL server. Fault :" + e.getMessage()); connection_.disconnect(); connection_ = null; return false; } }  public void releaseConnection() { connection_.disconnect(); connection_ = null; }  /**  *   * @param url  * @param method  * @param bulletin  * @param msgtype json or xml  * @return  */  public String sendRequest(URL url, Cord method, String message, String msgtype) {  String response = null;  if (setSSLConnection(url,method,msgtype)) {  try{ //Sending the asking to Remote server OutputStreamWriter author = new OutputStreamWriter(connection_.getOutputStream()); writer.write(bulletin); writer.flush(); writer.shut(); _responseCode = connection_.getResponseCode(); LOGGER.info("Response Lawmaking :" + _responseCode); // reading the response InputStreamReader reader = new InputStreamReader(connection_.getInputStream()); StringBuilder buf = new StringBuilder(); char[] cbuf = new char[ 2048 ]; int num; while ( -ane != (num = reader.read( cbuf ))) { buf.suspend(cbuf, 0, num ); } response = buf.toString();    }take hold of(Exception e){ response = "<EXCEPTION>Exception occurred while sending message</EXCEPTION>"; e.printStackTrace();  }    } releaseConnection(); render response; } }        

Finally, nosotros are going to add the main form of this awarding.

Add together the bundle com.bhaiti.kela.ssl.customer.app and add the below class to it.

          package com.bhaiti.kela.ssl.customer.app;   import coffee.net.URL;  import org.apache.commons.configuration.Configuration; import org.apache.eatables.configuration.PropertiesConfiguration;  import com.bhaiti.kela.mutual.config.ApplicationConfig; import com.bhaiti.kela.ssl.client.SSLClient;   public grade ClientApp {  public static void main(String[] args) { System.out.println("In main"); Configuration config = goose egg; //Load (String)configuration try {     String currentPath = System.getProperty("user.dir"); config = new PropertiesConfiguration(currentPath + "/" + "system.properties");  }catch(Exception e) { System.out.println("Exception in reading properties file : arrangement.properties"); e.printStackTrace(); System.exit(-1); }  ApplicationConfig ac = ApplicationConfig.getInstance(); air-conditioning.setKEYSTOREPATH((String)config.getProperty("KEYSTOREPATH")); ac.setTRUSTSTOREPATH((Cord)config.getProperty("TRUSTSTOREPATH")); ac.setKEYSTOREPW((String)config.getProperty("KEYSTOREPW")); ac.setTRUSTSTOREPW((String)config.getProperty("TRUSTSTOREPW")); ac.setKEYPASS((String)config.getProperty("KEYPASS")); air conditioning.setKeystoreType((String)config.getProperty("keystoreType")); air conditioning.setTrustAllCertificate((Cord)config.getProperty("trustAllCertificate")); ac.setKeymanageralgorithm((String)config.getProperty("keymanageralgorithm"));   try { //A Soap web service phone call SSLClient sslClient = SSLClient.getSSLClient(); Cord strurl ="https://localhost:23521/app/v1/myservice";//yous can add together all the urls in config file URL url = new URL(strurl); Cord method = "Postal service"; Cord message = "your soap message body"; String msgtype = "text/xml"; Cord response = sslClient.sendRequest(url, method, message, msgtype);  //A RESTFul Become web service call strurl ="https://localhost:23521/app/v1/test/Student.json?studentId=9999"; url = new URL(strurl); method = "Become"; message = ""; msgtype = "text/xml"; response = sslClient.sendRequest(url, method, message, msgtype);  //A RESTFul POST spider web service phone call strurl ="https://localhost:23521/app/v1/test/Student.json"; url = new URL(strurl); method = "Post"; message = "your json bulletin body"; msgtype = "text/xml"; response = sslClient.sendRequest(url, method, message, msgtype); }take hold of(Exception e) { e.printStackTrace(); } }  }        

Now y'all can select this file by correct-clicking and selecting, 'Run as Java Application.' Too, you can create a jar file and run it. For any help or information leave a comment.

Opinions expressed past DZone contributors are their own.

How To Configure Tls For Java Soap Service,

Source: https://dzone.com/articles/ssl-based-https-restful-and-soap-client-applicatio

Posted by: baxterfortits64.blogspot.com

0 Response to "How To Configure Tls For Java Soap Service"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel