I have a SafeNet 5100 eToken already with a valid certificate in it that I use to access a web application from my company that requires it (multi-factor authentication).
I'm creating a desktop application to access this website. I am already able to add the website's certificate to the TrustStore and get my certificate into a KeyStore.
What I've got so far is:
System.setProperty("javax.net.ssl.trustStore", "U:\\Certificados\\efau.truestore");
System.setProperty("javax.net.ssl.trustStoreType", "jks");
System.setProperty("javax.net.ssl.trustStorePassword", "oiadad");
KeyManagerFactory kFac;
SSLContext sslContext;
SSLSocketFactory sockFactory = null;
KeyStore ks;
try {
// load keystore present in windows and print aliases found (only one, so nextElement always prints same information (name of certificate inside usb token I want to open))
ks = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
ks.load(null, null);
System.out.println(ks.aliases().nextElement());
System.out.println(ks.aliases().nextElement());
// try to load my certificate specifically from all certificates and passes necessary token password to it
InputStream in = IOUtils.toInputStream(ks.aliases().nextElement(), "UTF-8");
System.out.println(in);
ks.load(in, password);
// print certificate to check if I have it
System.out.println(ks.getCertificate(ks.aliases().nextElement()));
// get ssl context and key manager factory
sslContext = SSLContext.getInstance("SSL", "SunJSSE");
kFac = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kFac.init(ks,null);
sslContext.init(kFac.getKeyManagers(), null, null);
sockFactory = sslContext.getSocketFactory();
// start connection with website
HttpsURLConnection conn = (HttpsURLConnection)new URL(<my-https-url>).openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setSSLSocketFactory(sockFactory);
int responseCode = conn.getResponseCode();
System.out.println("RESPONSE: " + responseCode);
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e1) {
e1.printStackTrace();
} catch (KeyManagementException e1) {
e1.printStackTrace();
}
When I run this code I get:
javax.net.ssl.SSLHandshakeException: Received fatal alert: decrypt_error
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.recvAlert(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at receita.system.monitoring.Ping.main(Ping.java:313)
And I get this error when I type the correct password for the token and when I type a wrong one, so I think I'm never passing it the password in the correct way.
Why am I receiving the exception?
--------- Updated ---------
I created a config file with the following information pointing to my PKCS11.dll library:
name = Aladdin
library = C:/WINDOWS/system32/eTPKCS11.dll
And in the main function I add:
SunPKCS11 newProvider = new SunPKCS11("u:/Certificados/etpkcs11.cfg");
Provider a = newProvider;
Security.addProvider(a);
KeyStore ks;
try {
ks = KeyStore.getInstance("PKCS11");
...
}
And now I'm getting this as an error:
java.security.KeyStoreException: PKCS11 not found
at java.security.KeyStore.getInstance(Unknown Source)
at receita.system.monitoring.Ping.main(Ping.java:292)
Caused by: java.security.NoSuchAlgorithmException: PKCS11 KeyStore not available
at sun.security.jca.GetInstance.getInstance(Unknown Source)
at java.security.Security.getImpl(Unknown Source)
... 2 more
I also tried to modify Keystore.getInstance to:
ks = KeyStore.getInstance("PKCS11", a);
and then I get this different error:
java.security.KeyStoreException: PKCS11 not found
at java.security.KeyStore.getInstance(Unknown Source)
at receita.system.monitoring.Ping.main(Ping.java:292)
Caused by: java.security.NoSuchAlgorithmException: no such algorithm: PKCS11 for provider SunPKCS11-Aladdin
at sun.security.jca.GetInstance.getService(Unknown Source)
at sun.security.jca.GetInstance.getInstance(Unknown Source)
at java.security.Security.getImpl(Unknown Source)
... 2 more
--------- Updated 2 (Working Code) ---------
My final working code is:
System.setProperty("javax.net.ssl.trustStore", "U:\\Certificados\\efau.truestore");
System.setProperty("javax.net.ssl.trustStoreType", "jks");
System.setProperty("javax.net.ssl.trustStorePassword", "oiadad");
KeyManagerFactory kFac;
SSLContext sslContext;
SSLSocketFactory sockFactory = null;
SunPKCS11 providerMSCAPI = new SunPKCS11("u:/Certificados/etpkcs11.cfg");
Provider a = providerMSCAPI;
Security.addProvider(a);
KeyStore ks;
try {
ks = KeyStore.getInstance("PKCS11");
ks.load(null, password);
InputStream in = IOUtils.toInputStream(ks.aliases().nextElement(), "UTF-8");
ks.load(in, password);
sslContext = SSLContext.getInstance("SSL", "SunJSSE");
kFac = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kFac.init(ks,null);
sslContext.init(kFac.getKeyManagers(), null, null);
sockFactory = sslContext.getSocketFactory();
HttpsURLConnection conn = (HttpsURLConnection)new URL(/*<my-url>*/).openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setSSLSocketFactory(sockFactory);
int responseCode = conn.getResponseCode();
InputStream inputstream = conn.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line = null;
String htmlResponse = "";
while ((line = bufferedreader.readLine()) != null) {
htmlResponse += line + "\n";
}
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e1) {
e1.printStackTrace();
} catch (KeyManagementException e1) {
e1.printStackTrace();
}
And I have to or set the debug argument in run configurations:
-Djava.security.debug=sunpkcs11
Or set the slot in the .cfg file:
name=SafeNet
library=C:\Windows\System32\eTPKCS11.dll
slot=4
The SunMSCAPI implementation isn't perfect (for example, if you have certificates with the same "friendly name", some will be inaccessible, since it's also the unique key used for the keystore alias). I'm not sure how well it works with hardware tokens.
Since your token seems to support PKCS#11, you might as well make use of the Oracle JRE's direct support for PKCS11 keystores.
Essentially, your token driver should come with a DLL implementing the PKCS#11 interface, and you need to point Java to it (as described in the PKCS#11 guide). For more flexibility, it might be more convenient to install the provider dynamically (see the paragraph that starts with "To install the provider dynamically, [...]".
Following your comments, perhaps you could use trial and error (by catching these exceptions) to find the right slot. Instead of using a configuration file, you could load the configuration from a string.
String password = "xxxxxxxxx";
String storeType = "PKCS11";
String configuration = "name = OpenSC\n"
+ "library = /usr/lib/opensc-pkcs11.so\n";
Provider provider = new sun.security.pkcs11.SunPKCS11(
new ByteArrayInputStream(configuration.getBytes("UTF-8")));
Security.addProvider(provider);
KeyStore keyStore = KeyStore.getInstance(storeType, provider);
keyStore.load(null, password.toCharArray());
If you add "slot=...\n" to the configuration string and use a loop to try various values until it stops throwing exceptions, it might work. You may need to remove the security providers where it failed, or change the name too. (I'm not suggesting this is a clean way to do it.)
By the way, if you don't want to hard-code your password (of course!) or load it from some configuration file, you can use a callback hander like this:
KeyStore keyStore = KeyStore.getInstance(storeType, provider);
LoadStoreParameter param = new LoadStoreParameter() {
#Override
public ProtectionParameter getProtectionParameter() {
return new KeyStore.CallbackHandlerProtection(... put your callback handler here...);
}
};
keyStore.load(param);
Your callback handler could be "new com.sun.security.auth.callback.DialogCallbackHandler()". I wouldn't generally advise using any of the com.sun.* or sun.* packages since they're not part of the public Java API, but you're using sun.security.pkcs11.SunPKCS11 here, so your code will be tied to this family of JREs anyway.
Try the below code to get the keystore from usb token using java
class Test {
public static void main(String args[]) throws IOException, GeneralSecurityException, DocumentException, CertificateVerificationException{
// Create instance of SunPKCS11 provider
String pkcs11Config = "name=eToken\nlibrary=C:\\Windows\\System32\\eps2003csp11.dll";
java.io.ByteArrayInputStream pkcs11ConfigStream = new java.io.ByteArrayInputStream(pkcs11Config.getBytes());
sun.security.pkcs11.SunPKCS11 providerPKCS11 = new sun.security.pkcs11.SunPKCS11(pkcs11ConfigStream);
java.security.Security.addProvider(providerPKCS11);
// Get provider KeyStore and login with PIN
String pin = "12345678";
java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS11", providerPKCS11);
keyStore.load(null, pin.toCharArray());
// Enumerate items (certificates and private keys) in th KeyStore
java.util.Enumeration<String> aliases = keyStore.aliases();
String alias = null;
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
System.out.println(alias);
}
}
}
Related
I have an app that serves to consume and update data to a webserver and, recently, the app owner decided to switch to a secure connection due to personal information stored.
The server is already set up as SNI and I have checked it using digicert, the server is working fine and seems to be set up correctly, but does not include the path *.host.com on its alternate names (I am unsure if this is normal or not for SNI).
The iOS worked like a charm, however on Android I get this error:
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
My current connection method looks like this:
URL url = new URL(postURL);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
SSLContext sc;
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new java.security.SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());
String userpass = "bob" + ":" + "12345678";
String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT);
conn.setRequestProperty("Authorization", basicAuth);
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.connect();
InputStream instream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder everything = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
everything.append(line);
}
JSONObject jsonObject = new JSONObject(everything.toString());
return jsonObject;
I'm not quite sure what's the issue here, but trying to connect to https://sni.velox.ch/ gives me a long answer that seems like a success.
Also, I do have the pem key for the certificate here with me, but I do not know how I add that in this context.
Usually you get this error when using a self-signed certificate, in which case you would have to use the certificate while making the request.
Additionally, you might be getting this error because of not including the path *.host.com.
You could try the below code to pass your certificate while building the HttpsURLConnection. Please don't forget to copy the ca.pem file to assets folder.
private HttpsURLConnection buildSslServerConnection() {
HttpsURLConnection urlConnection = null;
try {
// Load CAs from an InputStream
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(context.getAssets().open("ca.pem"));
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);
// Tell the URLConnection to use a SocketFactory from our SSLContext
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Authorization", "Basic" + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT));
urlConnection.setConnectTimeout(7000);
urlConnection.setReadTimeout(7000);
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setUseCaches(false);
urlConnection.setAllowUserInteraction(false);
urlConnection.setDoOutput(false);
} catch (KeyManagementException e) {
LOG.error("Error while checking server connectivity: ", e);
} catch (CertificateException e) {
LOG.error("Error while checking server connectivity: ", e);
} catch (FileNotFoundException e) {
LOG.error("Error while checking server connectivity: ", e);
} catch (KeyStoreException e) {
LOG.error("Error while checking server connectivity: ", e);
} catch (NoSuchAlgorithmException e) {
LOG.error("Error while checking server connectivity: ", e);
} catch (MalformedURLException e) {
LOG.error("Error while checking server connectivity: ", e);
} catch (IOException e) {
LOG.error("Error while checking server connectivity: ", e);
}
return urlConnection;
}
Hope this helps.
I am making a financial transaction android app. It requires SSL authentication and I successfully able to complete it(handshake between Android and Tomcat). I used keytool and openSSL to generate Server and client certificates. Tomcat certifcate format is JKS and android formate is BKS. I stored this BKS file in Raw folder and use this as follows:
public class NetworkCallSecure extends AsyncTask<String, Void, String> {
ResponseListener responseListener;
Activity activity;
ResultCodes code;
public NetworkCallSecure(Activity activity, ResponseListener responseListener, ResultCodes code) {
this.responseListener = responseListener;
this.activity = activity;
this.code = code;
}
#Override
protected String doInBackground(String... params) {
try{
System.setProperty("http.keepAlive", "false");
HttpsURLConnection .setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname,
SSLSession session) {
Log.d("HTTPS",hostname+":"+session);
return true;
}
});
char[] passwKey = "mypass".toCharArray();
KeyStore ks = KeyStore.getInstance("BKS");
InputStream in = activity.getResources().openRawResource(
R.raw.client);
InputStream is = activity.getResources().openRawResource(
R.raw.client);
ks.load(in, passwKey);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(ks, passwKey);
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(),
new X509TrustManager[] { new MyX509TrustManager(is,
passwKey) }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
URL url = new URL(params[0]);
HttpsURLConnection connection = (HttpsURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", "" + Integer.toString(params[1].getBytes().length));
connection.setDoOutput(true);
byte[] outputInBytes = params[1].getBytes("UTF-8");
OutputStream os = connection.getOutputStream();
os.write( outputInBytes );
os.close();
BufferedReader bin = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = bin.readLine()) != null) {
sb.append(line);
}
in.close();
is.close();
return sb.toString();
} catch (Exception e) { // should never happen
e.printStackTrace();
Log.d("Err", e.toString());
}
return "no result";
}
#Override
protected void onPostExecute(String result) {
responseListener.getResponse(result,code);
}
}
My Trustmanager class is:
public class MyX509TrustManager implements X509TrustManager {
X509TrustManager pkixTrustManager;
public MyX509TrustManager(InputStream trustStore, char[] password)
throws Exception {
// create a "default" JSSE X509TrustManager.
KeyStore ks = KeyStore.getInstance("BKS");
ks.load(trustStore, password);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(ks);
TrustManager tms[] = tmf.getTrustManagers();
/*
* Iterate over the returned trustmanagers, look for an instance of
* X509TrustManager. If found, use that as our "default" trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
pkixTrustManager = (X509TrustManager) tms[i];
return;
}
}
/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("Couldn't initialize");
}
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
try {
pkixTrustManager.checkClientTrusted(arg0, arg1);
} catch (CertificateException excep) {
// do any special handling here, or rethrow exception.
}
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
try {
pkixTrustManager.checkServerTrusted(arg0, arg1);
} catch (CertificateException excep) {
/*
* Possibly pop up a dialog box asking whether to trust the cert
* chain.
*/
}
}
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return pkixTrustManager.getAcceptedIssuers();
}
}
Now I want to register user using this HTTPS connection. The process is get details from user and send it to server. Server will verify these details and send confirmation PIN on user mobile (got this MSISDN in user details). User will enter this PIN and server will verify that PIN is same. After user is verified client app (user mobile) will generate a CSR and send it to server. Server will generate Certificate using this CSRand send it to client (mobile app).
Now my problem is I want to store this certificate where only my App can access this certificate. I am trying to save this in my BKS file in raw folder using this:
private boolean storeCertInKeystore(byte[] cert) {
try {
InputStream is = getResources().openRawResource(
R.raw.client);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream certstream = new ByteArrayInputStream(cert);
X509Certificate certificate = (X509Certificate) cf.generateCertificate(certstream);
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(is, "mypass".toCharArray());
keyStore.setCertificateEntry("mycert", certificate);
Log.d("My App Cert: ", "true");
return true;
} catch(Exception e) {
e.printStackTrace();
}
return false;
}
This code runs successfully but could not store cert in BKS file. I tried another way describe here but could not succeed. (I want to use this certificate later in my app for client authentication)
My Question is Q. How can I store this certificate so it can be only accessible by my app? And also I can delete this certificate when user registration expires.
Please help and thanks in advance.
Your issue is not with the keystore itself, but rather with the
location of the file where you're trying to store the new client
certificate!
The "RAW-folder" is part of your installed application package. So
you can "virtually" access it, and only READ, not WRITE!
Your best option, if you want your keystore to be private, is your
application sandboxed-private-folder(Internal storage).
You can't write in the RAW-folder, but you can write in your application private folder.
In the link that you provided, the storage/write location is in
fact the private folder. So it didn't work for you because you're
trying to "write in the Raw-Folder"
You probably know that already, but you can copy your file(R.raw.client)
from the "Raw-folder" to your application private folder. That way, you only use one keystore file(readable and writable).
EDITTED: "The code below works fine, no errors, no exceptions"
I'm aware of the grand amount of questions in regards to this topic, as well as the many blogs that google conjures up. I have read through them and have managed to come up with what I'm about to explain. My doubt lies in "is my approach correct? Does it have any side-effects?" and another question that is better asked as I explain my method.
I based this approach following this Android.Developres tutorial.
System.setProperty("jsse.enableSNIExtension", "false");
//Java 7 introduced SNI (enabled by default). The server I use is
// misconfigured I suppose and
// it sends an "Unrecognized Name" warning in the SSL handshake
// which breaks my web service.
// Load CA from an InputStream (CA would be saved in Raw file,
// and loaded as a raw resource)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(new FileInputStream("PATH_TO_CERT.crt"));
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);
// Create all-trusting host name verifier
// to avoid the following :
// java.security.cert.CertificateException: No name matching
// This is because Java by default verifies that the certificate CN (Common Name) is
// the same as host name in the URL. If they are not, the web service client fails.
HostnameVerifier allHostsValid = new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
};
//Install it
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL("https....");
urlConnection.setSSLSocketFactory(context.getSocketFactory());
try {
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
switch(urlConnection.getResponseCode()){
case 401:
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
System.out.println( sb.toString());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here is my other question, in the following line:
InputStream caInput = new BufferedInputStream(new FileInputStream("PATH_TO_CERT.crt"));
You see that the method forces me to have the certificate.crt preloaded onto raw file inside res folder. Is there a way (I have looked but have found 0 answers) to connect to the server and download said certificate.crt and save it on a private folder not accessible by the user?
i am a relative novice at Android and have had issues getting a simple SSL connection working to a java server.
I know the java server works as I tested it using the same keystore as the server and a java client.
The Android client does send something as the java server accepts a connection and displays a null value for a readline variable, and no error message.
I have my keystore, and truststore in bks format, and added to the res/raw folder.
Android Client:
SSLContext sslContext = SSLContext.getDefault();
KeyStore trustSt = KeyStore.getInstance("BKS");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
InputStream trustStoreStream = this.getResources().openRawResource(R.raw.truststore);
trustSt.load(trustStoreStream, "password".toCharArray());
trustManagerFactory.init(trustSt);
KeyStore keyStore = KeyStore.getInstance("BKS");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
InputStream keyStoreStream = this.getResources().openRawResource(R.raw.keystore);
keyStore.load(keyStoreStream, "password".toCharArray());
keyManagerFactory.init(keyStore, "password".toCharArray());
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
}
catch (NoSuchAlgorithmException nsae){Log.d("SSL", nsae.getMessage());}
catch (KeyStoreException kse){Log.d("SSL", kse.getMessage());}
catch (IOException ioe){Log.d("SSL", ioe.getMessage());}
catch (CertificateException ce){Log.d("SSL", ce.getMessage());}
catch (KeyManagementException kme){Log.d("SSL", kme.getMessage());}
catch(AccessControlException ace){Log.d("SSL", ace.getMessage());}
catch(UnrecoverableKeyException uke){Log.d("SSL", uke.getMessage());}
try{
//error catch
String error = "test";
sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
s = (SSLSocket) sslsocketfactory.createSocket("192.168.2.101", port);
outStream = s.getOutputStream();
outStreamWriter = new OutputStreamWriter(outStream);
bufferedWriter = new BufferedWriter(outStreamWriter);
bufferedWriter.write(error + "\n");
bufferedWriter.flush();
} //end try
catch (UnknownHostException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
finally{
if (s != null){
try {s.close();}
catch (IOException e) {e.printStackTrace();}
}
}//end finally
}
I have specified a truststore but do not not how to initialise the truststore on the socket.
Any help would be appreciated.
I think changing this line
sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
to use the SSLSocketFactory(KeyStore truststore) constructor may solve your problem.
sslsocketfactory = new SSLSocketFactory(trustSt);
I am trying to setup mutual authentication SSL connection between java host and android client. Don't know why its not getting connected. Below are the code of Android client app and Java server.
Client code:
private SSLContext createSSLContext(final Context cont){
SSLContext ssl_cont = null;
try {
Log.d(TAG, "TrustStore - Initializing");
KeyStore trustStore = KeyStore.getInstance("BKS");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
InputStream trustStoreStream = cont.getResources().openRawResource(R.raw.myclienttruststore);
trustStore.load(trustStoreStream, "client".toCharArray());
trustManagerFactory.init(trustStore);
Log.d(TAG, "TrustStore - Initialized");
// Setup keystore
Log.d(TAG, "KeyStore - Initializing");
KeyStore keyStore = KeyStore.getInstance("BKS");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
InputStream keyStoreStream = cont.getResources().openRawResource(R.raw.myclient);
keyStore.load(keyStoreStream, "client".toCharArray());
keyManagerFactory.init(keyStore, "client".toCharArray());
Log.d(TAG, "KeyStore - Initialized");
ssl_cont = SSLContext.getInstance("TLS");
ssl_cont.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
} catch (Exception e) {
// TODO Auto-generated catch block
alertbox("SSLClient", "ERROR: " + e.getMessage());
Log.d(TAG, "ERROR: " + e.getMessage());
}
return ssl_cont;
}
OnClickListener onConnClick = new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
// Setup the SSL context to use the truststore and keystore
Log.d(TAG, "Started..");
SSLContext ssl_context = createSSLContext(cont);
Log.d(TAG,"here 1...");
SSLSocketFactory socketFactory = (SSLSocketFactory) ssl_context.getSocketFactory();
Log.d(TAG,"here 2...");
socket = (SSLSocket) socketFactory.createSocket(ipadd.getText().toString().trim(), Integer.parseInt(port.getText().toString().trim()));
Log.d(TAG,"here 3...");
dataOut = new DataOutputStream(socket.getOutputStream());
dataIn = new DataInputStream(socket.getInputStream());
dataOut.writeUTF("Hello !!");
msgin.setText("Connected");
Log.d(TAG, "Completed..");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
msgin.setText("Not connected");
alertbox("Main", "ERROR: " + e.getMessage());
Log.d(TAG, "ERROR: " + e.getMessage());
}
}
};
Server code:
try {
mySSLServerFac = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
mySSLServerSocket = (SSLServerSocket) mySSLServerFac.createServerSocket(9999);
System.out.println("Listening on 9999\n");
mySSLSocket = (SSLSocket) mySSLServerSocket.accept();
DataInputStream input = new DataInputStream(mySSLSocket.getInputStream());
DataOutputStream output = new DataOutputStream(mySSLSocket.getOutputStream());
do{
System.out.println("Remote IP Address : " + mySSLSocket.getInetAddress());
msg = input.readUTF().toString();
System.out.println(msg);
java.util.Scanner sc = new java.util.Scanner(System.in);
output.writeUTF(sc.nextLine());
}while(msg != "exit");
System.out.println(msg);
} catch (Exception e) {
e.printStackTrace();
}
I am stuck with "No cipher suites in common" error at server. Since i am nowhere in SSL connection setup. Let me help if you find out the bug or major problem.
Here is the link i followed to create certificate and truststore. Truststore and kestore i have created are here
I am using Android 2.2 and BKSProvider 1.46, please let know where i am going wrong. I have to wind up this project as soon as possible.
Thanks in advance.
From the stack trace it looks like exception you caught does not contain a message.
Log.d(TAG, e.getMessage());
It has nothing to do with SSL.
It's solved ! Problem was with the truststore of java host, followed this post.
The trustStore needs to be specified for client/server as they are using the default trustStore, causing failure. Using -Djavax.net.ssl.trustStore=servertruststore.jks -Djavax.net.ssl.trustStorePassword=server on the server and creating own keystore & truststore at client allows the session to complete. It was the -Djavax.net.debug=ssl,handshake which helped lot.
The entire command is : java -Djavax.net.ssl.keyStore=server.jks -Djavax.net.ssl.keyStorePassword=server -Djavax.net.ssl.trustStore=servertruststore.jks -Djavax.net.ssl.trustStorePassword=server SSLServer
Now i am on to creating sslsession and multi-threaded programming.