I am trying to connect Azure SQL Database using Android Application, While connecting to the Azure SQL database, I am getting SSL Handshake aborted issue. I am using the latest android studio 4.1.2 version and the Android Version was Lollipop 5.0. and also I added a TLS certificate to the application.
Any idea how to fix it ??
Here is my java code :
public static void SetUpHttpsConnection(String urlString) {
String response = null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
System.out.println("Loading Certificate from Assets folder ....");
InputStream caInput = new BufferedInputStream(MainActivity.context.getAssets().open("ca-bundle.crt"));
X509Certificate caCertificate = (X509Certificate) cf.generateCertificate(caInput);
Certificate ca = cf.generateCertificate(caInput);
System.out.println("generate certificate .............");
System.out.println("ca : " + (caCertificate).getSubjectDN());
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", caCertificate);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
System.out.println(" Trust Manager Factory ------ ");
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context1 = SSLContext.getInstance("TLS");
//SSLContext context1 = SSLContext.getInstance("TLSv1.2");
System.out.println(" ------------------------------- ");
//context1.init(null, tmf.getTrustManagers(), null);
System.out.println("SSL context ---- :" + context1);
context1.init(null, new X509TrustManager[]{new X509TrustManager(){
#SuppressLint("TrustAllX509TrustManager")
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
#SuppressLint("TrustAllX509TrustManager")
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
context1.getSocketFactory());
System.out.println("Trust Certificates ----- ");
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL(urlString);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
if (urlConnection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConn = (HttpsURLConnection) urlConnection;
httpsConn.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0,null));
httpsConn.setHostnameVerifier(new AllowAllHostnameVerifier());
httpsConn.setRequestProperty("Connection", "Keep-Alive");
httpsConn.setRequestProperty("Charset", "UTF-8");
}
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(2500);
urlConnection.setReadTimeout(3500);
urlConnection.setRequestProperty("Content-Type", "application/json");
int statuscode = urlConnection.getResponseCode();
Log.d("Status code :", Integer.toString(statuscode));
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
response = streamToString(inputStream);
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readStream(InputStream is) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("US-ASCII")));
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
if (reader != null) {
reader.close();
}
return total.toString();
}
private static String streamToString(InputStream inputStream) throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = rd.readLine())!= null) {
sb.append(line);
}
return sb.toString();
}
#SuppressLint("StaticFieldLeak")
private class Azure_Connection extends AsyncTask<String, Void, Iterable<Test>> {
String res = "";
private String rowKey;
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this, "Please wait...", Toast.LENGTH_SHORT)
.show();
}
protected Iterable<Test> doInBackground(String... arg0) {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
System.out.println("Reading JDBC Driver");
String UserName = "username#iwavesqlserver";
String Passwrd = "*******";
String ConnectionString = "jdbc:jtds:sqlserver://iwavesqlserver.database.windows.net:1433/iwave_db_1;loginTimeout=300;ssl=require;" +
"integratedSecurity=true;encrypt=false;TrustServerCertificate=true;hostNameInCertificate=*.database.windows.net;";
System.out.println(" .......... Connecting to the SQL Database .......... ");
String urlString = "https://portal.azure.com/#home";
SetUpHttpsConnection(urlString);
try {
Connection connection = DriverManager.getConnection(ConnectionString, UserName, Passwrd);
if (connection != null) {
System.out.println("Database connection success");
}
Statement stmt = Objects.requireNonNull(connection).createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT * FROM test");
log.info("Database Connection test : " + connection);
} catch (SQLException e) {
e.printStackTrace();
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
}
Error message :
I/System.out: Connection Exception : java.sql.SQLException: Network error IOException: SSL handshake aborted: ssl=0xebc432c8: I/O error during system call, Broken pipe
W/System.err: java.sql.SQLException: Network error IOException: SSL handshake aborted: ssl=0xebc432c8: I/O error during system call, Broken pipe
W/System.err: at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:436)
W/System.err: at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(DriverManager.java:569)
W/System.err: at java.sql.DriverManager.getConnection(DriverManager.java:219)
at com.iwavesys.cloudazure.MainActivity$Azure_Connection.doInBackground(MainActivity.java:381)
at com.iwavesys.cloudazure.MainActivity$Azure_Connection.doInBackground(MainActivity.java:316)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
W/System.err: Caused by: javax.net.ssl.SSLHandshakeException: SSL handshake aborted: ssl=0xebc432c8: I/O error during system call, Broken pipe
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
I am not sure this is the correct way to add certificates and get a connection to the Azure SQL database. please anyone help me to solve this issue.
Thank you.
I have a requirement to convert certain bash scripts to java and one such script connects to a server using openssl with a vanity-url as a parameter to check if that is connectable using that vanity-url. See command below
/usr/bin/openssl s_client -connect api.sys.found1.cf.company.com:443 -servername www.app.company.com 2>/dev/null
I wanted to do the similar activity in java and test the connectivity. Any ideas on how to make a open-ssl connection using Java .. Is this something that I need to use external Library ?
I was able to achieve this by referring the document over here
Basically, a SSLEngine needs to be created and make a successful handshake along with SNI
private SocketChannel createSocketChannel() throws IOException {
InetSocketAddress socketAddress = new InetSocketAddress(PROXY_ADDRESS, PROXY_PORT);
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(socketAddress);
socketChannel.configureBlocking(false);
return socketChannel;
}
private SSLContext createSSLContext() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext sslContext = SSLContext.getInstance(TLS_VERSION);
sslContext.init(null,null,null);
return sslContext;
}
private SSLEngine createSSLEngine() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext sslContext = createSSLContext();
SSLEngine sslEngine = sslContext.createSSLEngine(PROXY_ADDRESS, PROXY_PORT);
sslEngine.setUseClientMode(true);
List<SNIServerName> serverNameList = new ArrayList<>();
serverNameList.add(new SNIHostName(SNI_HOST_NAME));
SSLParameters sslParameters = sslEngine.getSSLParameters();
sslParameters.setServerNames(serverNameList);
sslEngine.setSSLParameters(sslParameters);
return sslEngine;
}
After creating SSLEngine, the handShake has to begin
SocketChannel channel = createSocketChannel();
SSLEngine sslEngine = createSSLEngine();
doHandShake(sslEngine,channel);
private void doHandShake(SSLEngine sslEngine, SocketChannel socketChannel) throws Exception {
System.out.println("Going to do Handshake");
SSLSession session = sslEngine.getSession();
ByteBuffer myAppData = ByteBuffer.allocate(session.getApplicationBufferSize());
ByteBuffer peerAppData = ByteBuffer.allocate(session.getApplicationBufferSize());
ByteBuffer myNetData = ByteBuffer.allocate(session.getPacketBufferSize());
ByteBuffer peerNetData = ByteBuffer.allocate(session.getPacketBufferSize());
sslEngine.beginHandshake();
SSLEngineResult result;
handshakeStatus = sslEngine.getHandshakeStatus();
while (handshakeStatus != SSLEngineResult.HandshakeStatus.FINISHED &&
handshakeStatus != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
switch (handshakeStatus) {
case NEED_UNWRAP:
if (! (socketChannel.read(peerNetData) <0)) {
peerNetData.flip();
result = sslEngine.unwrap(peerNetData,peerAppData);
peerNetData.compact();
handshakeStatus = result.getHandshakeStatus();
switch (result.getStatus()) {
case OK:
break;
}
}
break;
case NEED_WRAP:
myNetData.clear() ;// Empty the local network packet buffer
result = sslEngine.wrap(myAppData,myNetData);
handshakeStatus = result.getHandshakeStatus();
switch (result.getStatus()) {
case OK:
myNetData.flip();
while (myNetData.hasRemaining()) {
socketChannel.write(myNetData);
}
}
break;
case NEED_TASK:
Runnable task = sslEngine.getDelegatedTask();
if (null!=task) {
task.run();
}
handshakeStatus = sslEngine.getHandshakeStatus();
break;
}
}
Once the handShake is done. you can get the Principal object
Principal principal = sslEngine.getSession().getPeerPrincipal();
if (principal.getName().contains(SNI_HOST_NAME)) {
System.out.println("available ... ");
}else {
System.out.println("Not available");
}
call isAliasExists with your values ,
isAliasExists("api.sys.found1.cf.company.com","www.app.company.com");
Returns true if your alias (servername) is part of the cert,
private static boolean isAliasExists(String hostName, String alias) throws Exception {
String host;
int port;
String[] parts = hostName.split(":");
host = parts[0];
port = (parts.length == 1) ? 443 : Integer.parseInt(parts[1]);
// key store password
char[] passphrase = "changeit".toCharArray();
File file = new File("jssecacerts");
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory factory = context.getSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println("Certificate is already trusted");
} catch (SSLException e) {
e.printStackTrace();
}
X509Certificate[] chain = tm.chain;
List<String> altNames=new ArrayList<String>();
for (X509Certificate cert: chain)
{
altNames.addAll(getSubjectAltNames(cert));
}
for(String altName: altNames) {
if(altName.trim().contains(alias))
return true;
}
if (chain == null) {
System.out.println("Could not obtain server certificate chain");
return false;
}
return false;
}
Returns list of alternative names from cert,
private static List<String> getSubjectAltNames(X509Certificate certificate) throws CertificateParsingException {
List<String> result = new ArrayList<>();
try {
Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames();
if (subjectAltNames == null) {
return Collections.emptyList();
}
for (Object subjectAltName : subjectAltNames) {
List<?> entry = (List<?>) subjectAltName;
if (entry == null || entry.size() < 2) {
continue;
}
Integer altNameType = (Integer) entry.get(0);
if (altNameType == null) {
continue;
}
String altName = (String) entry.get(1);
if (altName != null) {
result.add(altName);
}
}
return result;
} catch (CertificateParsingException e) {
return Collections.emptyList();
}
}
custom trust manager,
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
// throw new UnsupportedOperationException();
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
throw new UnsupportedOperationException();
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
Without really knowing what SNI was I tried to get some insight with the test-program shown below.
I don't know the output from the openssl s_client command, but the test-program might prove to be a starting point. When the javax.net.debug output is turned on a lot of output is dumped of which only a few lines are relevant (see also the comments). That is a bit annoying and I do not have an easy solution for that. The TrustAllServers class can be reworked to inspect the certificates you expect to receive from the server (a.ka. host) for a particular domain. There might be other options (e.g. the socket's handshake methods) but this is as far as I got.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedTrustManager;
// https://stackoverflow.com/questions/56005883/java-equivalent-to-openssl-s-client-command
// Please use latest Java 8 version, bugs are around in earlier versions.
public class ServerNameTest {
public static void main(String[] args) {
// SSL debug options, see https://stackoverflow.com/q/23659564/3080094 and https://access.redhat.com/solutions/973783
// System.setProperty("javax.net.debug", "all");
// System.setProperty("javax.net.debug", "ssl:handshake");
// System.setProperty("jsse.enableSNIExtension", "true"); // "true" is the default
try {
ServerNameTest sn = new ServerNameTest();
// This will show 2 different server certificate chains.
// Note this is a random server - please pick your own one.
sn.test("major.io", "rackerhacker.com");
sn.test("major.io", "major.io");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
/*
* With javax.net.debug output you should see something like:
* <pre>
* *** ClientHello
* ...
* Extension server_name, server_name: [type=host_name (0), value=DOMAIN;]
* ...
* *** ServerHello
* ...
* Extension server_name, server_name:
* ...
* </pre>
* Note that if the server does not provide a value for server_name,
* it does not actually mean the server does not support SNI/server_name (see https://serverfault.com/a/506303)
*/
void test(String host, String domain) throws Exception {
SSLParameters sslParams = new SSLParameters();
if (domain != null && !domain.isEmpty()) {
sslParams.setServerNames(Arrays.asList(new SNIHostName(domain)));
}
// Only for webservers: set endpoint algorithm to HTTPS
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
SSLSocketFactory sslsf = serverTrustingSSLFactory();
try (SSLSocket socket = (SSLSocket) sslsf.createSocket()) {
socket.setSSLParameters(sslParams);
socket.setSoTimeout(3_000);
System.out.println("Connecting to " + host + " for domain " + domain);
socket.connect(new InetSocketAddress(host, 443), 3_000);
// Trigger actual connection by getting the session.
socket.getSession();
System.out.println("Connected to remote " + socket.getRemoteSocketAddress());
try (BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) {
try (OutputStream out = socket.getOutputStream()) {
System.out.println(">> OPTIONS");
out.write("OPTIONS * HTTP/1.1\r\n\r\n".getBytes(StandardCharsets.UTF_8));
System.out.println("<< " + input.readLine());
}
} catch (Exception e) {
System.err.println("No line read: " + e);
}
}
}
SSLSocketFactory serverTrustingSSLFactory() throws Exception {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, trustManager(), null);
return ctx.getSocketFactory();
}
TrustManager[] trustManager() throws Exception {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init( (KeyStore) null);
// Must use "extended" type versus the default javax.net.ssl.X509TrustManager,
// otherwise the error "No subject alternative DNS name matching" keeps showing up.
X509ExtendedTrustManager defaultManager = null;
for (TrustManager trustManager : tmf.getTrustManagers()) {
if (trustManager instanceof X509ExtendedTrustManager) {
defaultManager = (X509ExtendedTrustManager) trustManager;
break;
}
}
if (defaultManager == null) {
throw new RuntimeException("Cannot find default X509ExtendedTrustManager");
}
return new TrustManager[] { new TrustAllServers(defaultManager) };
}
static void printChain(X509Certificate[] chain) {
try {
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
System.out.println("Cert[" + i + "] " + cert.getSubjectX500Principal() + " :alt: " + cert.getSubjectAlternativeNames());
}
} catch (Exception e) {
e.printStackTrace();
}
}
static class TrustAllServers extends X509ExtendedTrustManager {
final X509ExtendedTrustManager defaultManager;
public TrustAllServers(X509ExtendedTrustManager defaultManager) {
this.defaultManager = defaultManager;
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
defaultManager.checkServerTrusted(chain, authType);
} catch (Exception e) {
System.err.println("Untrusted server: " + e);
}
printChain(chain);
}
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
try {
defaultManager.checkServerTrusted(chain, authType, socket);
} catch (Exception e) {
System.err.println("Untrusted server for socket: " + e);
}
printChain(chain);
}
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
try {
defaultManager.checkServerTrusted(chain, authType, engine);
} catch (Exception e) {
System.err.println("Untrusted server for engine: " + e);
}
printChain(chain);
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
defaultManager.checkClientTrusted(chain, authType);
}
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
defaultManager.checkClientTrusted(chain, authType, socket);
}
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
defaultManager.checkClientTrusted(chain, authType, engine);
}
public X509Certificate[] getAcceptedIssuers() {
return defaultManager.getAcceptedIssuers();
}
}
}
I'm writing a mod for a game in Java to check to see if the player has voted using a server methods to get the Steam ID. I can't get a good response from what I'm seeing. Every response is an IOException which I've had print out "Invalid Response Code".
I've tried implementing what I've seen in similar mods for https connections, but I am not getting anywhere with it.
try {
HttpsURLConnection connection = (HttpsURLConnection) new URL( "https://somewebsite.com/"
).openConnection();
connection.setSSLSocketFactory(createTrustAllSocketFactory());
int responseCode = connection.getResponseCode();
if (responseCode != 200) throw new IOException("Invalid response code.");
InputStream in = connection.getInputStream();
ByteArrayOutputStream stringBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
int len = 0;
while (len != -1) {
stringBuffer.write(buffer, 0, len);
len = in.read(buffer);
}
String result = new String(stringBuffer.toByteArray(), StandardCharsets.UTF_8);
if (result.equals("1")) {
try {
performer.addMoney(MonetaryConstants.COIN_COPPER * 5);
performer.getCommunicator().sendNormalServerMessage("Thanks for voting! Your rewards have been added to your bank.");
} catch (IOException ex) {
performer.getCommunicator().sendAlertServerMessage("Failed to add reward. Please submit a support ticket.");
ex.printStackTrace();
}
}
private static SSLSocketFactory createTrustAllSocketFactory() throws IOException {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = {
new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
/* empty */
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
/* empty */
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
ctx.init(null, trustManagers, null);
return ctx.getSocketFactory();
} catch (GeneralSecurityException ex) {
throw new IOException(ex);
}
}
The expectation is that when the command is issued in-game, the server will call the external site with the player's steam ID and generate either a 0 or 1 based on if they have voted.
Actual is getting a bad response code.
I am trying to connect to a URL from a desktop app, and I get the error indicated in the Title of my question. When I check the URL in browser, it works fine though.
The error is coming for getInputStream.
When i further tried to investigate to check what the error is by doing getErrorStream i saw it is giving nullpointerexception.
Please guide.
Below is my code
public void call() throws IOException, ParserConfigurationException, SAXException, TransformerException
{
OutputStreamWriter out = null;
URL url = null;
BufferedReader in = null;
String username = "test";
String password = "test";
String xmlDoc =
String xmlDoc = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?> <document schema=\"mySchema.xsd\"><data><start-date>2012-03-10T00:00:00</start-date><end-date>2017-01-13T10:43:00</end-date></data></document>";
try {
// ----Avoid certificate Error Code Start--------
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
SSLContext sc = null;
try
{
sc = SSLContext.getInstance("SSL");
}
catch (NoSuchAlgorithmException e) {
e.getMessage();
}
try
{
sc.init(null, trustAllCerts, new java.security.SecureRandom());
}
catch (KeyManagementException e) {
e.getMessage();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
url = new URL("https://myURL.com?username="+username+"&password="+password+"&xmlDocument="+xmlDoc+"");
//URLEncoder.encode("https://service.bioguiden.se/mpaallexport.asmx/Export?username="+username+"&password="+password+"&xmlDocument="+xmlDoc+"","UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.connect();
out = new OutputStreamWriter(conn.getOutputStream());
StringBuffer data = new StringBuffer();
out.write(data.toString());
out.flush();
// Read the response
StringBuffer rsp = new StringBuffer();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
rsp.append(line);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The code below is supposed to ignore all certificates:
public class Application {
public static void main(String... args) {
System.out.println("Initiating... ");
// 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) {
}
}
};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};
SSLContext sc = null;
// Install the all-trusting trust manager
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (GeneralSecurityException e) {
}
// Now you can access an https URL without having the certificate in the truststore
try {
URL url = new URL("https://localhost:30009/iPG/c2b/multione");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(hv);
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
However I keep getting the error:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1002)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
at post.Application.main(Application.java:66)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(InputRecord.java:505)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983)
I don't understand why this is the case.