Quite new with Dropwizard.
I found a lot of solution to deal with Jersey and ssl self signed certificate.
Dropwizard version is 0.9.2
I have tried to set a SSLContext but I get
The method sslContext(SSLContext) is undefined for the type JerseyClientBuilder
Code:
TrustManager[] certs = new TrustManager[]{
new X509TrustManager() {
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
};
public static class TrustAllHostNameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
private Client getWebClient(AppConfiguration configuration, Environment env) {
SSLContext ctx = SSLContext.getInstance("SSL");
ctx.init(null, certs, new SecureRandom());
Client client = new JerseyClientBuilder(env)
.using(configuration.getJerseyClient())
.sslContext(ctx)
.build("MyClient");
return client;
}
The configuration part:
private JerseyClientConfiguration jerseyClient = new JerseyClientConfiguration();
public JerseyClientConfiguration getJerseyClient() {
return jerseyClient;
}
I have found a simple solution just using the configuration
jerseyClient:
tls:
verifyHostname: false
trustSelfSignedCertificates: true
I think to create an insecure client in 0.9.2 you would use a Registry of ConnectionSocketFactory, something like...
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
}
#Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
throws java.security.cert.CertificateException {
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} }, new SecureRandom());
final SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslConnectionSocketFactory)
.register("http", PlainConnectionSocketFactory.INSTANCE)
.build();
builder.using(registry);
Client client = new JerseyClientBuilder(env)
.using(configuration.getJerseyClient())
.using(registry)
.build("MyInsecureClient");
Related
I am using SOAP call using cxf, and getting ssl readHandshakeRecord exception
unwinding now org.apache.cxf.interceptor.Fault: Could not send Message.
at
reason:
java.base/java.lang.Thread.run(Unknown Source)
Caused by: javax.net.ssl.SSLException: SSLException invoking https://myservice/Services: readHandshakeRecord
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
.......
I also try to skip ssl validation with trust all certs
static {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
} };
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (Exception e) {
log.error("Exception ssl ",e);
}
HostnameVerifier allHostsValid = new HostnameVerifier()
{
#Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
};
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
but still getting error
I also tries with TLSClientParameters
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(Hello.class);
factory.setAddress(address);
Hello portType = (Hello) factory.create();
try {
HostnameVerifier allHostsValid = new HostnameVerifier()
{
#Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
};
HTTPConduit httpCon = (HTTPConduit) ClientProxy.getClient(portType).getConduit();
TLSClientParameters parameters = new TLSClientParameters();
parameters.setSSLSocketFactory(sslSocketFactory);
parameters.setDisableCNCheck(true);
parameters.setHostnameVerifier(allHostsValid);
parameters.setTrustManagers(new TrustManager[] { new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws java.security.cert.CertificateException {
}
#Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws java.security.cert.CertificateException {
}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}});
httpCon.setTlsClientParameters(parameters);
} catch (Exception e) {
System.out.ptintln( e);
}
but still getting same error
Need your valuable help
thank you in advance!
How can I achieve curl -k in feign client?
I know I can do this. Just want to know if there's a way to ignore or disable.
new Client.Default(SSLSocketFactory sslContextFactory, HostnameVerifier hostnameVerifier)
Disclaimer
You should not actually do this for a number of very good reasons. The easiest way to fix SSL issues is to actually follow SSL best practices and use valid certificates. There are excellent projects online such as https://letsencrypt.org/ that will even allow you to get great security for free if the host is publicly accessible (if it has a real hostname that can be verified against).
USE AT YOUR OWN RISK. MAKE SURE YOU UNDERSTAND YOU ARE VIOLATING A LOT OF BEST PRACTICES AND ONLY USE THIS IF YOU UNDERSTAND THAT.
If you cause some type of major problem using this example code, you are liable.
Real talk
I had the same problem dealing with internal (publicly non-accessible) services that I wanted to call from a spring-boot application and I solved it using the following code.
Brief Overview
A great many people will tell you that you can either accept all certificates, hard-code your particular cert in it, or something else. You can actually allow only certain trusted hosts through the codepath, which is what I am attempting here for an additional layer of security.
In this example code, you can pass multiple hosts to the classes and it should allow requests to only those hosts to be issued with invalid certificates, and everything else will go through the normal chain of command.
This is not really production grade code, but hopefully you will get some use out of it.
Enough lecturing, what follows may interest you the most.
The Code
This is using for Java 8 and spring-boot.
Configuration
#Configuration
public class FeignClientConfiguration {
#Bean
public Client client() throws NoSuchAlgorithmException,
KeyManagementException {
return new Client.Default(
new NaiveSSLSocketFactory("your.host.here"),
new NaiveHostnameVerifier("your.host.here"));
}
}
NaiveHostnameVerifier
public class NaiveHostnameVerifier implements HostnameVerifier {
private final Set<String> naivelyTrustedHostnames;
private final HostnameVerifier hostnameVerifier =
HttpsURLConnection.getDefaultHostnameVerifier();
public NaiveHostnameVerifier(String ... naivelyTrustedHostnames) {
this.naivelyTrustedHostnames =
Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(naivelyTrustedHostnames)));
}
#Override
public boolean verify(String hostname, SSLSession session) {
return naivelyTrustedHostnames.contains(hostname) ||
hostnameVerifier.verify(hostname, session);
}
}
NaiveSSLSocketFactory
public class NaiveSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory sslSocketFactory =
(SSLSocketFactory) SSLSocketFactory.getDefault();
private final SSLContext alwaysAllowSslContext;
private final Set<String> naivelyTrustedHostnames;
public NaiveSSLSocketFactory(String ... naivelyTrustedHostnames)
throws NoSuchAlgorithmException, KeyManagementException {
this.naivelyTrustedHostnames =
Collections.unmodifiableSet(
new HashSet<>(Arrays.asList(naivelyTrustedHostnames)));
alwaysAllowSslContext = SSLContext.getInstance("TLS");
TrustManager tm = new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
alwaysAllowSslContext.init(null, new TrustManager[] { tm }, null);
}
#Override
public String[] getDefaultCipherSuites() {
return sslSocketFactory.getDefaultCipherSuites();
}
#Override
public String[] getSupportedCipherSuites() {
return sslSocketFactory.getSupportedCipherSuites();
}
#Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return (naivelyTrustedHostnames.contains(host))
? alwaysAllowSslContext.getSocketFactory().createSocket(socket, host, port, autoClose)
: sslSocketFactory.createSocket(socket, host, port, autoClose);
}
#Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return (naivelyTrustedHostnames.contains(host))
? alwaysAllowSslContext.getSocketFactory().createSocket(host, port)
: sslSocketFactory.createSocket(host, port);
}
#Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException, UnknownHostException {
return (naivelyTrustedHostnames.contains(host))
? alwaysAllowSslContext.getSocketFactory().createSocket(host, port, localAddress, localPort)
: sslSocketFactory.createSocket(host, port, localAddress, localPort);
}
#Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return (naivelyTrustedHostnames.contains(host.getHostName()))
? alwaysAllowSslContext.getSocketFactory().createSocket(host, port)
: sslSocketFactory.createSocket(host, port);
}
#Override
public Socket createSocket(InetAddress host, int port, InetAddress localHost, int localPort) throws IOException {
return (naivelyTrustedHostnames.contains(host.getHostName()))
? alwaysAllowSslContext.getSocketFactory().createSocket(host, port, localHost, localPort)
: sslSocketFactory.createSocket(host, port, localHost, localPort);
}
}
References
I borrowed heavily from this answer:
Trusting all certificates using HttpClient over HTTPS
When using Spring Cloud Netflix >= 1.4.4.RELEASE you can also do the following:
Add okhttp client maven dependency:
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
And add the following properties:
feign.httpclient.disableSslValidation=true
feign.httpclient.enabled=false
feign.okhttp.enabled=true
Reference:
https://github.com/spring-cloud/spring-cloud-netflix/issues/2729
With current versions of spring-cloud-starter-openfeign suppressing hostname verification works as follows.
When using apache httpclient:
In application.yml set disable-ssl-validation property
feign.httpclient.disable-ssl-validation: true
In pom.xml add feign-httpclient dependency.
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
If you prefer okhttp you must enable okhttp with another application property and add feign-okhttp dependency:
feign.httpclient.disableSslValidation=true
feign.httpclient.enabled=false
feign.okhttp.enabled=true
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
For httpclient5 (hc5), property disable-ssl-validation sadly does not turn off hostname verification (yet?), here's the ticket: https://github.com/spring-cloud/spring-cloud-openfeign/issues/625
Application properties for enabling hc5.
feign.httpclient.disableSslValidation=true
feign.httpclient.hc5.enabled=true
Maven dependency to add
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-hc5</artifactId>
</dependency>
NOTE: The tricky part for me was that I missed to add feign-httpclient as a dependency. In this case, a default feign client with enabled hostname verification is used.
Override via feign configuration
#Bean
public Client feignClient()
{
Client trustSSLSockets = new Client.Default(getSSLSocketFactory(), new NoopHostnameVerifier());
return trustSSLSockets;
}
private SSLSocketFactory getSSLSocketFactory() {
try {
TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
#Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
return sslContext.getSocketFactory();
} catch (Exception exception) {
}
return null;
}
feign.httpclient.disableSslValidation = true is not worked for me.
Create Client bean in Configuration by the following code is worked:
import feign.Client;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.ssl.SSLContexts;
import org.springframework.context.annotation.Bean;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
public class ClientConfiguration {
#Bean
public Client feignClient() {
return new Client.Default(getSSLSocketFactory(), new NoopHostnameVerifier());
}
private SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
return sslContext.getSocketFactory();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
pom.xml might needs add dependencies:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
Disable ssl Validation by adding below property in application.yaml.
feign.httpclient.disableSslValidation=true
or as a VM argument
-Dfeign.httpclient.disableSslValidation=true
Add below class to your repository and use this class as configuration
this piece of code worked for me:
#Configuration
public class SSLSocketClient {
#Bean
public Client feignClient() {
return new Client.Default(getSSLSocketFactory(),getHostnameVerifier());
}
//SSLSocketFactory
// Install the all-trusting trust manager
public static SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
//TrustManager
// trust manager that does not validate certificate chains
private static TrustManager[] getTrustManager() {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
#Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[]{};
}
}};
return trustAllCerts;
}
//HostnameVerifier
public static HostnameVerifier getHostnameVerifier() {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession)
{
return true;
}
};
return hostnameVerifier;
}}
i'm using imap endpoint and i try to ignore SSL certificat by using:
the First class DummySSLSocketFactory :
public class DummySSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory factory;
public DummySSLSocketFactory() {
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null,
new TrustManager[] { new
DummyTrustManager()},
null);
factory = (SSLSocketFactory)sslcontext.getSocketFactory();
} catch(Exception ex) {
// ignore
}
}
public static SocketFactory getDefault() {
return new DummySSLSocketFactory();
}
public Socket createSocket() throws IOException {
return factory.createSocket();
}
public Socket createSocket(Socket socket, String s, int i, boolean flag)
throws IOException {
return factory.createSocket(socket, s, i, flag);
}
public Socket createSocket(InetAddress inaddr, int i,
InetAddress inaddr1, int j) throws IOException {
return factory.createSocket(inaddr, i, inaddr1, j);
}
public Socket createSocket(InetAddress inaddr, int i)
throws IOException {
return factory.createSocket(inaddr, i);
}
public Socket createSocket(String s, int i, InetAddress inaddr, int j)
throws IOException {
return factory.createSocket(s, i, inaddr, j);
}
public Socket createSocket(String s, int i) throws IOException {
return factory.createSocket(s, i);
}
public String[] getDefaultCipherSuites() {
return factory.getDefaultCipherSuites();
}
public String[] getSupportedCipherSuites() {
return factory.getSupportedCipherSuites();
}
}
the second class DummyTrustManager :
public class DummyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] cert, String authType) {
// everything is trusted
}
public void checkServerTrusted(X509Certificate[] cert, String authType) {
// everything is trusted
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
the third class AllowAll to set java mail propeties:
public class AllowAll {
public void setsslproperties() {
//DummySSLSocketFactory easy = new EasySSLProtocolSocketFactory();
Properties props = System.getProperties();
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.imap.ssl.socketFactory.class","com.mycompany.imapssl.DummySSLSocketFactory");
props.setProperty("mail.imap.ssl.socketFactory.fallback", "false");
props.setProperty("mail.imap.socketFactory.port", "993");
Session session = Session.getInstance(props, null);
}
}
How can i associate this to the iMap EiP to ignore SSL Certificate ?
this is the route:
<route id="timerToLog">
<from uri="imaps://server:993?username=user_name&password=pass"/>
<log message="ok"/>
If you're using a recent version of JavaMail, set the mail.imap.ssl.trust property to the name of the host you want to trust. That avoids the need to create your own socket factory.
I see on this page how to do https
http://sonatype.github.com/async-http-client/ssl.html
but what if I just want to ignore and accept any certificate as in this environment I don't care about man in the middle right now since it is in an isolated environment and I am just doing some stuff for automated testing on QA data.
Maybe my question instead is how to fake out the SSL in java's SSL stack so it accepts any cert on the other end(this is not bi-directional since it is https).
The common code for the client in the above link is
char[] keyStorePassword = "changeit".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
//ks.load(keyStoreStream, keyStorePassword);
char[] certificatePassword = "changeit".toCharArray();
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, certificatePassword);
KeyManager[] keyManagers = kmf.getKeyManagers();
javax.net.ssl.TrustManager tm = new MyTrustMgr();
javax.net.ssl.TrustManager[] trustManagers = new javax.net.ssl.TrustManager[]{tm };
SecureRandom secureRandom = new SecureRandom();
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(keyManagers, trustManagers, secureRandom);
return ctx;
okay, working off that, I found out this which is still not working for some reason
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { tm }, null);
return ctx;
thanks,
Dean
5 years late to the party, but I was facing the same problem today and your question came up pretty high in Google searches. So maybe my answer will help someone else.
Taking your code of creating the SSLContext, this code will create an AsyncHttpClient that will ignore (or blindly accept) all SSL certificates:
AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder()
.setSSLContext(createSslContext())
.build();
httpClient = new AsyncHttpClient(config);
The createSslContext method is, as mentioned above, an exact copy & paste of the code you had in your answer:
private SSLContext createSslContext() throws Exception {
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { tm }, null);
return ctx;
}
The above examples work with Async HTTP Client 1.9.40 & Java 1.8
Ive been developing a rss reader which needs to make a mutal ssl authentication.
Ive managed to get the user certificate using the Keychain API and have got what seems to a mostly working SSLSocketFactory.
But whenever i try to make a connection to the server i get a 401 Unauthorized error, i feel its probably something to do with the way i am setting up my SSL Connection and my general code. If anyone can help point out what im doing wrong and what i need to do i would be greatly appreciative.
Main Activity:
public class AliasLoader extends AsyncTask<Void, Void, X509Certificate[]>
{
X509Certificate[] chain = null;
#Override protected X509Certificate[] doInBackground(Void... params) {
android.os.Debug.waitForDebugger();
if(!SavedAlias.isEmpty())
{
try {
PrivateKey key2 = KeyChain.getPrivateKey(getApplicationContext(), SavedAlias);
setPrivateKey(key2);
chain = KeyChain.getCertificateChain(getApplicationContext(),SavedAlias);
setCertificate(chain);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
else
{
this.cancel(true);
}
return chain;
}
#Override
protected void onPostExecute(X509Certificate[] chain)
{
if(chain != null)
{
HttpClient client = CustomSSLSocketFactory.getNewHttpClient(context, getAlias(), chain, key);
String formDataServiceUrl = "https://android.diif.r.mil.uk";
WebView wv = (WebView) findViewById(R.id.rssFeedItemView);
HttpPost post = new HttpPost(formDataServiceUrl);
final HttpGet request = new HttpGet(formDataServiceUrl);
HttpResponse result = null;
try {
result = client.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wv.loadUrl(formDataServiceUrl);
}
else
{
Toast.makeText(getApplicationContext(), "Certificate is Empty", Toast.LENGTH_LONG).show();
}
}
}
CustomSSLSocketFactory:
public class CustomSSLSocketFactory extends SSLSocketFactory {
public static KeyStore rootCAtrustStore = null;
public static KeyStore clientKeyStore = null;
SSLContext sslContext = SSLContext.getInstance("TLS");
Context context;
/**
* Constructor.
*/
public CustomSSLSocketFactory(Context context, KeyStore keystore, String keyStorePassword, KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(keystore, keyStorePassword, truststore);
this.context = context;
// custom TrustManager,trusts all servers
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
Log.i("CLIENT CERTIFICATES", "Loaded client certificates: " + keystore.size());
// initialize key manager factory with the client certificate
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore,null);
sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { tm }, null);
//sslContext.init(null, new TrustManager[]{tm}, null);
}
#Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
#Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
/**
* Create new HttpClient with CustomSSLSocketFactory.
*/
public static HttpClient getNewHttpClient(Context context, String alias, X509Certificate[] chain, PrivateKey key) {
try {
// This is method from tutorial ----------------------------------------------------
//The root CA Trust Store
rootCAtrustStore = KeyStore.getInstance("BKS");
rootCAtrustStore.load(null);
//InputStream in = context.getResources().openRawResource(com.DII.RSS_Viewer.R.raw.rootca);
//rootCAtrustStore.load(in, "PASSWORD".toCharArray());
//The Keystore with client certificates.
//clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
clientKeyStore = KeyStore.getInstance("pkcs12");
clientKeyStore.load(null);
// client certificate is stored in android's keystore
if((alias != null) && (chain != null))
{
Key pKey = key;
clientKeyStore.setKeyEntry(alias, pKey, "password".toCharArray(), chain);
}
//SSLSocketFactory sf = new CustomSSLSocketFactory(context, clientKeyStore, "password", rootCAtrustStore);
SSLSocketFactory sf = new SSLSocketFactory(clientKeyStore, "password");
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", (SocketFactory) sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
}
catch (Exception e)
{
return new DefaultHttpClient();
}
}
}