Spring boot WebServiceTemplate SoapActionCallback - set keystore and TLS - java

I've this code in java 8
String u = "https://test.com.asmx?WSDL";
String pwd = "aaaa";
String pathP12 = "1234.p12";
KeyStore ks = KeyStore.getInstance("PKCS12");
FileInputStream fis = new FileInputStream(pathP12);
ks.load(fis, pwd.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, pwd.toCharArray());
URL url = new URL(u);
SSLContext sc = SSLContext.getInstance("TLSv1");
sc.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(sc.getSocketFactory());
System.out.println("After url connection");
How can i set TLSv1 and keystore in a SoapActionCallback in Spring Boot
ProvaResponse response = (ProvaResponse) getWebServiceTemplate().marshalSendAndReceive(
request,
new SoapActionCallback("http://www.test.com/Prova")
);

Related

SOAP Request with HTTP Client with client certification connection timed out Exception

I am trying to hit an url with client certification have generate key with:
keytool -genkey -alias server -keyalg RSA -keystore /example.jks -validity 10950
and key store with:
keytool -import -trustcacerts -alias root -file /example.cer -keystore /example.jks
and trying to connect:
System.out.println("------------------------------------------- In SendRequest ------------------------------------################");
SSLContext context = SSLContext.getInstance("TLS");
Certificate cert=getCertificate();
URL url = new URL("url");
URLConnection urlConnection = url.openConnection();
HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) urlConnection;
SSLSocketFactory sslSocketFactory = getFactory();
httpsUrlConnection.setSSLSocketFactory(sslSocketFactory);
DataOutputStream wr = new DataOutputStream(httpsUrlConnection.getOutputStream());
System.out.println(wr.toString());
File req_xml = new File("request.xml");
//SOAPMessage req = TestCase.createSoapSubsribeRequest("SUBSCRIBE");
HttpPost post = new HttpPost("url");
post.setEntity(new InputStreamEntity(new FileInputStream(req_xml), req_xml.length()));
post.setHeader("Content-type", "text/xml; charset=UTF-8");
//post.setHeader("SOAPAction", "");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
LOG.info("************************************************************RESPONSE****************"+response.getStatusLine());
// SOAP response(xml) get String res_xml = EntityUtils.toString(response.getEntity());
LOG.info("Response"+res_xml);
}
private SSLSocketFactory getFactory( ) {
try{
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
System.out.println("------------------------------------------- In getFactory ------------------------------------################");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
//InputStream keyInput = new FileInputStream(pKeyFile);
String password = "obsmesh";
char[] passwd = password.toCharArray(example.jks");
keystore.load(is, passwd);
// keyInput.close();
keyManagerFactory.init(keystore, password.toCharArray());
System.out.println("------------------------------------------- In jsdkl ------------------------------------################");
SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] trust = null;
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
return context.getSocketFactory();
}catch(Exception e){
System.out.println(e);
}
return null;
}
Try with this code I hope it will help you.
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File("//your jks file path "), "//key password here",
new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
try {
File req_xml = new File("// your request xml file path");
HttpPost post = new HttpPost("//https client url");
post.setEntity(new InputStreamEntity(new FileInputStream(req_xml), req_xml.length()));
post.setHeader("Content-type", "text/xml; charset=UTF-8");
System.out.println("Executing request " + post.getRequestLine());
CloseableHttpResponse response = httpclient.execute(post);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(entity);
System.out.println(response.getEntity());
} finally {
response.close();
}
} finally {
httpclient.close();
}

Android/Eclipse Open a file Outside the MainActivity in a Plugin

I have a problem with my Android Phonegap App.
I created a plugin to send Data from HTML/JAVASCRIPT to Java and Java will send this DATA to a
Server with HTTPS post.
To get this Worke I need to Open a ssl.crt (certification) from my Asset folder.
In the Cordova Class this function dose work because it extends the CordovaActivity.
My Plugin Class : public class ConnectPlugin extends CordovaPlugin
Here is the Login method:
protected String tryLogin_2(String d1) throws CertificateException, FileNotFoundException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException
{
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = new BufferedInputStream(this.getAssets().open("ssl.crt"));
java.security.cert.Certificate ca;
try {
ca = cf.generateCertificate(caInput);
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String httpsURL = "https://URL.com";
OutputStreamWriter request = null;
DataInputStream response_2 = null;
String parameters = "1="+d1;
String response = null;
try
{
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setSSLSocketFactory(context.getSocketFactory());
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
request = new OutputStreamWriter(con.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(con.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
//Response from server after login process will be stored in response variable.
response = sb.toString();
isr.close();
reader.close();
}
catch(IOException e)
{
response = "Error"; // Error
}
return response;
}
The problem now is "The method getAssets() is undefined for the type ConnectPlugin".
I can't use the getAssets() method outside the Main Class.
In my MainClass the obove code work 100% fine and sends a request to my server.
But not in my Plugin Class.
Use
cordova.getActivity().getAssets().open("ssl.crt"));

critical policy qualifiers present in certificate

I reciverd a .p12 certificate, that I need to use a web service. If I import the certificate in my browser, I can access the service, but if I try to perform a POST request, I get this error:
Caused by: java.security.cert.CertPathValidatorException: critical policy qualifiers present in certificate
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:139)
at sun.security.provider.certpath.PKIXCertPathValidator.doValidate(PKIXCertPathValidator.java:328)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:178)
at java.security.cert.CertPathValidator.validate(CertPathValidator.java:250)
at sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:275)
... 24 more
Here is my code:
KeyStore clientStore = KeyStore.getInstance("PKCS12");
clientStore.load(new FileInputStream("client.p12"), "password".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientStore, "password".toCharArray());
KeyManager[] kms = kmf.getKeyManagers();
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream("client.keystore"), "password".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
TrustManager[] tms = tmf.getTrustManagers();
SSLContext sslContext = null;
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kms, tms, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
URL url = new URL("https://cistest.apis-it.hr:8446/g2bservis");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String query = "<SendDocument></SendDocument>";
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","text");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
DataInputStream input = new DataInputStream( con.getInputStream() );
for( int c = input.read(); c != -1; c = input.read() )
System.out.print( (char)c );
input.close();
System.out.println("Resp Code:"+con .getResponseCode());
System.out.println("Resp Message:"+ con .getResponseMessage());
The excetion happens on con.getOutputStream()
I resolved the problem by exporting the server's certificate from chrome and using that instead of the default root certificate I had for the page. I noticed that certificate might be the problem, when I was able to open the page in chrome but not in firefox.

Java - Download zip from a SSL HTTP url (with keystore/trustore)

I'm trying to download a zip file from an url but the url returns a 404 page with the app.
When I try with firefox, it just asked the keystore so I put it and it works : I can download the ZIP file.
I don't really understand what I'm doing wrong.
Here is my code
URL url = new URL(reportInfo.getURI().toString());
HttpsURLConnection con = (HttpsURLConnection) url
.openConnection();
/*
* Keystore manager
*/
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance("SunX509");
String pKeyPassword = GSBConstants.KEYSTORE_PASSWORD;
KeyStore keyStore = KeyStore.getInstance("JKS");
InputStream keyInput = new FileInputStream(new File(
cc.getWorkingDir() + File.separator
+ GSBConstants.KEYSTOREJKS_NAME));
keyStore.load(keyInput, pKeyPassword.toCharArray());
keyInput.close();
keyManagerFactory
.init(keyStore, pKeyPassword.toCharArray());
/*
* Trustore manager
*/
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance("SunX509");
KeyStore trustStore = KeyStore.getInstance("JKS");
InputStream trustInput = new FileInputStream(new File(
cc.getWorkingDir() + File.separator
+ GSBConstants.TRUSTORE_NAME));
String pTrustPassword = GSBConstants.TRUSTORE_PASSWORD;
trustStore.load(trustInput, pTrustPassword.toCharArray());
trustInput.close();
trustManagerFactory.init(trustStore);
SSLContext context = SSLContext.getInstance("SSL");
context.init(keyManagerFactory.getKeyManagers(),
trustManagerFactory.getTrustManagers(),
new SecureRandom());
SSLContext.setDefault(context);
SSLSocketFactory sockFact = context.getSocketFactory();
con.setSSLSocketFactory(sockFact);
// Check for errors
int responseCode = con.getResponseCode();
InputStream inputStream;
if (responseCode == HttpURLConnection.HTTP_OK) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
OutputStream output = new FileOutputStream("test.zip");
// Process the response
BufferedReader reader;
String line = null;
reader = new BufferedReader(new InputStreamReader(
inputStream));
while ((line = reader.readLine()) != null) {
output.write(line.getBytes());
}
output.close();
inputStream.close();
Any ideas ?
I don't have any exceptions.

webpage in webview is blank

I am using the code below to connect to https site. But the result is always a blank page. I have already searched alot. Any help will be appreciated.
public boolean shouldOverrideUrlLoading(WebView view, String url)
{ try
{
InputStream keyStoreStream = getResources().openRawResource(R.raw.jssecacerts);
KeyStore keyStore = null;
keyStore = KeyStore.getInstance("BKS");
keyStore.load(keyStoreStream, "mypwd".toCharArray());
KeyManagerFactory keyManagerFactory = null;
keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "mypwd".toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, null);
alertbox("before response", url);
URL url1 = new URL(url);
HttpsURLConnection urlConnection = (HttpsURLConnection) url1.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();
alertbox("response", convertToString(in));
view.loadData(convertToString(in), "text/html", "utf-8");
}
catch(Exception e)
{
e.printStackTrace();
}
return true;
}
have you tried something as simple as
webview.loadUrl("URL HERE");

Categories

Resources