Here is my code
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
I am getting following exception
java.security.cert.CertificateException: No name matching www.sandbox.freelancer.com found
As per I know this site does not have proper Certificate. But any how I have to login into this site. Any suggestion will be appreciated. Thanks.
Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
Now access an https URL
try {
URL url = new URL("https://www.sandbox.freelancer.com");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
BufferedReader br =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
} catch (MalformedURLException e) {
}
You can save the certificate (get it in firefox), and then add the certificate to the keystore, and then configure your app to use that keystore.
Related
I'm trying to consume a web service, in which we import a certificate to the JDK's cacert file. But I can't understand how to "set" the HttpsURLConnection object the cert that it must use to be able to execute the web service.
I read that once the certificate was installed in the cacert file, it was no longer necessary to indicate anything when connecting to the web service.
I am currently skipping the KeyStore and TrustStore validation to invoke the web service.
This is my code:
public void tokenFotoCteNOCHOProd(String url) throws IOException {
HttpsURLConnection conn = null;
String params = "";
String res = "";
try {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
/**/
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
/**/
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
params = "someParams";
URL url = new URL(url);
conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setConnectTimeout(3000);
try (OutputStream os = conn.getOutputStream()) {
os.write(params.getBytes(StandardCharsets.UTF_8));
os.flush();
res = getRespWS(conn);//get resp..
}
} catch (KeyManagementException | NoSuchAlgorithmException | ClassCastException | JsonParseException e) {
LOGGER.info("error", e);
}
}
A client developed in Java using JDK 1.6. I am consuming API in the java code. Whenever I hit this API from soapui or from JDK 1.7 it is working perfectly fine but when I tried to hit this API using JDK 1.6, it is returning the error.
com.sun.xml.internal.ws.client.ClientTransportException: HTTP transport error: java.net.SocketException: Connection reset
I have tried by developing client using WSDL and using HTTPSURLConnection, with both mechanism, I am getting the same error. It seems there is nothing wrong with the code. I am unable to find out the way for the resolution.
Wireshark Result:
When I ran the jar from JDK 1.7, I can see the result in Wireshark, the protocol is TSLv1 but when I tried to run the jar from 1.6, the protocol has been changed to SSLv2.
Is it possible to change protocol in the code or on the system where we are calling jar?
Here is my code:
public String myFun(String sender) throws IOException,
NoSuchAlgorithmException, KeyManagementException{
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManager[] trustManager = getTrustManager();
sslContext.init(null, trustManager, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
try{
String inquiryRequest = inquiryRequest = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v5=\"http://xxxxxxx\">\n"
+"<soapenv:Header>\n"
+"</soapenv:Header>\n"
+"<soapenv:Body>\n"
+"<v5:single.smsReq>\n"
+"<sender>"+sender+"</sender>\n"
+"</v5:single.smsReq>\n"
+"</soapenv:Body>\n"
+"</soapenv:Envelope>";
URL url =new URL ("https://xxxx:xx/xx");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("content-type","application/xml");
conn.setRequestProperty("Authorization","Basic xxx");
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(inquiryRequest);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
conn.disconnect();
return response.toString();
}catch(Exception e){
return null;
}
}
private TrustManager[] getTrustManager() {
TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String t) {
}
public void checkServerTrusted(X509Certificate[] certs, String t) {
}
}
};
return certs;
}
In SSLContext you can setup your own SSlContext TSLv1 or SSLv2 then call sslContext.init with trusted certificates. And, add it to your HttpsURLConnection as the DefaultSSLSocketFactory.
System.setProperty ("jsse.enableSNIExtension", "false");
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManager[] trustManager = getTrustManager();
sslContext.init(null, trustManager, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HostnameVerifier hostNameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hostNameVerifier);
When trying to access web service from secured testing environment with SSL certificate getting the issue below.
com.android.volley.NoConnectionError: javax.net.ssl.SSLProtocolException: Read error: ssl=0xa35dad40: Failure in SSL library, usually a protocol error
error:100000d7:SSL routines:OPENSSL_internal:SSL_HANDSHAKE_FAILURE (external/boringssl/src/ssl/s3_pkt.c:402 0xa3630912:0x00000000)
I have tried with volley and basic java code, still getting the same issue. When I used the same code for secured development environment with different certificate its working fine. Whereas its not working in testing environment for specific bandwidths (Airtel 3G, 4G). It is working fine with all the environments(Testing & Dev) for 2G bandwidths.
Don't know where the problem occurs. Help me in sorting out this issue.
I have added the code snippet below,
Responsecallback responsecallback;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
testing(mBase_Url);
}
public void testing(String urls) {
String result = "";
try {
URL url = new URL(urls);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(getSSLCertificate()); // Tell the URLConnection to use a SocketFactory from our SSLContext
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("country", "IN");
String query = builder.build().getEncodedQuery();
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(query);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); //,8192
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
responsecallback.displayResponse(result);
in.close();
} catch (IOException e) {
result = e.toString();
Log.e(TAG, "HTTP Error Result=" + result);
responsecallback.displayResponse(result);
}
}
private SSLSocketFactory getSSLCertificate() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("PKCS12");
// your trusted certificates (root and any intermediate certs)
InputStream in = getResources().openRawResource(R.raw.xxxxxx); //SSL Certificate - P12 formate
String password = "XXXXXXX"; // Certificate password
char[] pwd = password.toCharArray();
try {
trusted.load(in, pwd);
} finally {
in.close();
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(trusted, pwd);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(trusted);
SSLContext context = SSLContext.getInstance("SSL");
context.init(kmf.getKeyManagers(), getWrappedTrustManagers(), new SecureRandom());
return context.getSocketFactory();
} catch (Exception e) {
Log.e(TAG, "Exception e=" + e.toString());
throw new AssertionError(e);
}
}
private TrustManager[] getWrappedTrustManagers() {
return new TrustManager[]{
new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
X509Certificate[] myTrustedAnchors = new X509Certificate[0];
return null;
}
}
};
}
I'm getting javax.net.ssl.SSLHandshakeException: Connection closed by peer when i try to make https request from android app using HttpsURLConnection
Above the code for to make request and return a Bitmap.
protected Bitmap doInBackground(String... params) {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
HttpsURLConnection connection = (HttpsURLConnection)
new URL("www.example.com.br").openConnection();
connection.setHostnameVerifier(getHostnameVerifier("www.example.com.br");
connection.setRequestMethod("GET");
connection.setConnectTimeout(3000);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.connect();
setCookieActivity(connection.getHeaderField("Set-Cookie"));
return BitmapFactory.decodeStream(connection.getInputStream());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private HostnameVerifier getHostnameVerifier(final String url) {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
HostnameVerifier hv =
HttpsURLConnection.getDefaultHostnameVerifier();
return hv.verify(url, session);
}
};
return hostnameVerifier;
}
I already tried many thing, but i get the same exception
This link works for many, but not for me.
telling java to accept self-signed ssl certificate
I am trying to read the content of the URL with the code down below, but get an 403 error:
https://api.kraken.com/0/public/Time
The URL is reachable in the Problem or via Rest-Connection-Test-Pages like https://apigee.com without a problem. The code works for other HTTPS-Urls just fine. I have no clue what could be wrong here:
public class HttpsClient{
public static void main(String[] args)
{
new HttpsClient().testIt();
}
private void testIt(){
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
;
}
String https_url = "https://api.kraken.com/0/public/Time";
URL url;
HttpsURLConnection con = null;
try {
url = new URL(https_url);
con = (HttpsURLConnection)url.openConnection();
//dumpl all cert info
print_https_cert(con);
try{
System.out.println("****** Content of the URL ********");
BufferedReader br =
new BufferedReader(
new InputStreamReader(con.getInputStream()));
String input;
while ((input = br.readLine()) != null){
System.out.println(input);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
#Override
public X509Certificate[] getAcceptedIssuers(){return null;}
#Override
public void checkClientTrusted(X509Certificate[] certs, String authType){}
#Override
public void checkServerTrusted(X509Certificate[] certs, String authType){}
}};
}