Menu
Hello Everyone,
I have done Posting request to https URL(using ssl)in c sharp very easily.
Now I am trying to do the same in Java. I already installed JSSE successfully. Next thing i have to do is to set certificate (i already have valid certificate).
Please, can anyone tell me how to set my certificate? ?
Thanks much for attention
<i>
</i>mport java.io.*;
import java.net.*;
import java.security.cert.*;
import javax.net.ssl.*;
public class HttpsPost {
public static void main(String[] args) throws Exception {
SSLContext sslctx = SSLContext.getInstance("SSL");
sslctx.init(null, new X509TrustManager[] { new MyTrustManager()
}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sslc tx.getSocketFactory());
URL url = new URL("https://www.xxxx.dk/htbin/tell2");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.println("f1=abc&f2=xyz");
ps.close();
con.connect();
if (con.getResponseCode() == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new
InputStreamReader(con.getInputStream()));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
con.disconnect();
}
}
class MyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String
authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String
authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
Thanks a lot for replying to me
But thing is that i want to indicate in code my own certificate. I did it in c# as follows:
...
X509Certificate2 certificate = new X509Certificate2(strCertFile, strCertPwd);
...
//Add Client Certificate
WebReq.ClientCertificates.Add(certificate);
...
It is not the whole code, just wanted to show how I add my custom certificate (strCertFile), which i have in my project. I want to do same in Java, and could not find out how to do that? ?[/QUOTE]
[CODE]
//Post Request with custom Certificate
private string PostSSL(string strPage, string strBuffer)
{
try
{
//Our postvars
byte[] buffer = Encoding.UTF8.GetBytes(strBuffer);
//Initialisation
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(strPage);
//Our method is post, otherwise the buffer (postvars) would be useless
WebReq.Method = "POST";
WebReq.KeepAlive = false;
//Import Client Certificate
string strCertFile = Application.StartupPath +
CConsts.csFolder_Certificate + global::E_Terminal.Properties.appl.Default.ClientCertFile;
string strCertPwd = global::E_Terminal.Properties.appl.Default.ClientCertPass;
X509Certificate2 certificate = new X509Certificate2(strCertFile, strCertPwd);
//We use form contentType, for the postvars.
WebReq.ContentType = "application/x-www-form-urlencoded";
//The length of the buffer (postvars) is used as contentlength.
WebReq.ContentLength = buffer.Length;
//Add Client Certificate
WebReq.ClientCertificates.Add(certificate);
WebReq.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
//We open a stream for writing the postvars
Stream PostData = WebReq.GetRequestStream();
//Now we write, and afterwards, we close. Closing is always important!
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
//Console.WriteLine(_Answer.ReadToEnd());
return _Answer.ReadToEnd();
}
catch (Exception ex)
{
CUtils.ErrorHandler(ex);
return String.Empty;
}
}
[/CODE]
Thanks again,
But I am writing console application not the web application, therefore i dont need to Set up Tomcat to Require Client Authentication. Can you have a look to my code in C#? i just want the same in java
[CODE]
[/QUOTE]
//Post Request with custom Certificate
private string PostSSL(string strPage, string strBuffer)
{
try
{
//Our postvars
byte[] buffer = Encoding.UTF8.GetBytes(strBuffer);
//Initialisation
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(strPage);
//Our method is post, otherwise the buffer (postvars) would be useless
WebReq.Method = "POST";
WebReq.KeepAlive = false;
//Import Client Certificate
string strCertFile = Application.StartupPath +
CConsts.csFolder_Certificate + global::E_Terminal.Properties.appl.Default.ClientCertFile;
string strCertPwd = global::E_Terminal.Properties.appl.Default.ClientCertPass;
X509Certificate2 certificate = new X509Certificate2(strCertFile, strCertPwd);
//We use form contentType, for the postvars.
WebReq.ContentType = "application/x-www-form-urlencoded";
//The length of the buffer (postvars) is used as contentlength.
WebReq.ContentLength = buffer.Length;
//Add Client Certificate
WebReq.ClientCertificates.Add(certificate);
WebReq.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
//We open a stream for writing the postvars
Stream PostData = WebReq.GetRequestStream();
//Now we write, and afterwards, we close. Closing is always important!
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
//Console.WriteLine(_Answer.ReadToEnd());
return _Answer.ReadToEnd();
}
catch (Exception ex)
{
CUtils.ErrorHandler(ex);
return String.Empty;
}
}
[/CODE]
[CODE]
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.trustStoreType", "jks");
System.setProperty("javax.net.ssl.keyStore", "C:\Program Files\Java\jdk1.6.0_18\jre\bin\5000049.p12");
System.setProperty("javax.net.ssl.trustStore", "C:\Program Files\Java\jdk1.6.0_18\jre\lib\security\cacerts");
System.setProperty("javax.net.ssl.keyStorePassword", "mypass");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
String httpsURL = "myurl";
URL url = new URL(httpsURL);
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
URLConnection conn = url.openConnection();
conn.getInputStream();
...
[/CODE]
Thanks again, i followed all steps, then even i used Portecle- which allowed me to install trusted certificate. And all went good, but code still give me error:
[CODE]
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.trustStoreType", "jks");
System.setProperty("javax.net.ssl.keyStore", "C:\Program Files\Java\jdk1.6.0_18\jre\bin\5000049.p12");
System.setProperty("javax.net.ssl.trustStore", "C:\Program Files\Java\jdk1.6.0_18\jre\lib\security\cacerts");
System.setProperty("javax.net.ssl.keyStorePassword", "mypass");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
String httpsURL = "myurl";
URL url = new URL(httpsURL);
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
URLConnection conn = url.openConnection();
conn.getInputStream();
...
[/CODE]
Then it still gives the following error:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target[/QUOTE]
[CODE]
//you have to import following:
import java.io.*;
import java.net.*;
import java.security.Security.*;
import com.sun.net.ssl.*;
import java.security.KeyStore;
. . .
//firstly put ur certs directly in Project Directory
//then you just have to change Red strings to your data
public static String PostSSL(String [COLOR="red"]strBuffer[/COLOR]) {
try {
//for HttpsURLConnection we need to set this property
System.setProperty("java.protocol.handler.pkgs",
"com.sun.net.ssl.internal.www.protocol");
String KEYSTORE = "", TRUESTORE = "";
//put your keystore cert directly in Project Directory
KEYSTORE = "[COLOR="red"]mykeycert[/COLOR].p12";
//set Keystore password
final String KEYSTOREPASS = "[COLOR="red"]yourKeyPass[/COLOR]";
//put your cacerts directly in Project Directory
TRUESTORE = "[COLOR="red"]cacerts[/COLOR]";
//set Truestore password
final String TRUESTOREPASS= "[COLOR="red"]yourTruePass[/COLOR]";
//my server URL
String httpsURL = "https://[COLOR="red"]yourserver[/COLOR]";
URL url = new URL(httpsURL);
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(KEYSTORE), KEYSTOREPASS.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, KEYSTOREPASS.toCharArray());
SSLContext sslctx2 = SSLContext.getInstance("SSLv3");
sslctx2.init(kmf.getKeyManagers(), null, null);
KeyStore ksTrust = KeyStore.getInstance("JKS");
ksTrust.load(new FileInputStream(TRUESTORE), TRUESTOREPASS.toCharArray());
//just tested if my certificate was imported in root Cacert
java.security.cert.Certificate cert = ksTrust.getCertificate("myCert");
//TrustManager's decide whether to allow connections.
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ksTrust);
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.trustStoreType", "jks");
System.setProperty("javax.net.ssl.keyStore", KEYSTORE);
System.setProperty("javax.net.ssl.trustStore", TRUESTORE);
System.setProperty("javax.net.debug", "ssl");
System.setProperty("javax.net.ssl.keyStorePassword", KEYSTOREPASS);
System.setProperty("javax.net.ssl.trustStorePassword", TRUESTOREPASS);
sslctx2.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
byte[] buffer = strBuffer.getBytes("UTF-8");
//******
HttpsURLConnection.setDefaultSSLSocketFactory(sslctx2.getSocketFactory());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.write(buffer, 0, buffer.length);
ps.close();
con.connect();
//get Response after SSL connection
String line = "";
String line2 = "";
int myRes = con.getResponseCode();
if (myRes == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
line = br.readLine();
line2 = line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
con.disconnect();
return line2;
} catch (Exception e) {
return "";
}
[/CODE]
try {
//for HttpsURLConnection we need to set this property
System.setProperty("java.protocol.handler.pkgs",
"com.sun.net.ssl.internal.www.protocol");
String KEYSTORE = "", truststore = "";
//put your keystore cert directly in Project Directory
KEYSTORE = "keystore";
//set Keystore password
final String KEYSTOREPASS = "changeit";
//put your cacerts directly in Project Directory
truststore = "cacerts";
//set Truestore password
final String TRUESTOREPASS= "changeit";
//my server URL
String httpsURL = "https://dir-staging.surescripts.net/directory/Directory6dot1/v6_1?id=12346";
URL url = new URL(httpsURL);
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(KEYSTORE), KEYSTOREPASS.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, KEYSTOREPASS.toCharArray());
SSLContext sslctx2 = SSLContext.getInstance("SSLv3");
sslctx2.init(kmf.getKeyManagers(), null, null);
KeyStore ksTrust = KeyStore.getInstance("JKS");
ksTrust.load(new FileInputStream(truststore), TRUESTOREPASS.toCharArray());
//just tested if my certificate was imported in root Cacert
java.security.cert.Certificate cert = ksTrust.getCertificate("addcertificate");
//TrustManager's decide whether to allow connections.
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ksTrust);
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.trustStoreType", "jks");
System.setProperty("javax.net.ssl.keyStore", KEYSTORE);
System.setProperty("javax.net.ssl.trustStore", truststore);
System.setProperty("javax.net.debug", "ssl");
System.setProperty("javax.net.ssl.keyStorePassword", KEYSTOREPASS);
System.setProperty("javax.net.ssl.trustStorePassword", TRUESTOREPASS);
sslctx2.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
byte[] buffer = file.getBytes("UTF-8");
//******
HttpsURLConnection.setDefaultSSLSocketFactory(sslctx2.getSocketFactory());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.write(buffer, 0, buffer.length);
ps.close();
con.connect();
//get Response after SSL connection
String line = "";
String line2 = "";
int myRes = con.getResponseCode();
if (myRes == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
line = br.readLine();
line2 = line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
con.disconnect();
return line2;
}
catch (Exception e) {
return "";
}
}
0.1.9 — BETA 4.26