Error obtaining i5 Keymanager and Trustmanager - ssl

Im trying to use send to paypal.
Im getting an error stating that my trustmanager has not been initialized. (I think).
This is my first steps into SSL so I may not have this set up correctly. Im getting SSlConfigurationException.
public static SSLContext setupClientSSL(String certPath, String certPassword)
throws SSLConfigurationException {
SSLContext sslContext = null;
try {
KeyManagerFactory kmf =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore ks = p12ToKeyStore(certPath, certPassword);
kmf.init(ks, certPassword.toCharArray());
//sslContext = getSSLContext(kmf.getKeyManagers());
sslContext = SSLContext.getInstance("SSL", "IBMJSSE2");
} catch (NoSuchAlgorithmException e) {
throw new SSLConfigurationException(e.getMessage(), e);
} catch (KeyStoreException e) {
throw new SSLConfigurationException(e.getMessage(), e);
} catch (UnrecoverableKeyException e) {
throw new SSLConfigurationException(e.getMessage(), e);
} catch (CertificateException e) {
throw new SSLConfigurationException(e.getMessage(), e);
} catch (NoSuchProviderException e) {
throw new SSLConfigurationException(e.getMessage(), e);
} catch (IOException e) {
throw new SSLConfigurationException(e.getMessage(), e);
}
return sslContext;
}

The Information Center has documentation for using the Java Secure Socket Extension including setup and example code.

Related

CXF RESTful Client

I have a rest org.apache.cxf.jaxrs.client.WebClient client for testing:
WebClient client = WebClient.create(URL);
and I want to make https request with cxf jax-rs
How can I do it? Examples?
ok, this is my solution:
public static void configureSSLOnTheClient(WebClient client,
String keyStoreFileName, String keyStorePassword,
String trustStoreFileName, String trustStorePassword) {
HTTPConduit httpConduit = (HTTPConduit) WebClient.getConfig(client).getConduit();
try {
TLSClientParameters tlsParams = new TLSClientParameters();
KeyStore keyStore;
KeyStore trustStore;
try {
keyStore = KeyStore.getInstance("JKS");
keyStore.load(ClassLoader.getSystemResourceAsStream(keyStoreFileName), keyStorePassword.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
trustStore = KeyStore.getInstance("JKS");
trustStore.load(ClassLoader.getSystemResourceAsStream(trustStoreFileName), trustStorePassword.toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
tlsParams.setSSLSocketFactory(sslContext.getSocketFactory());
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// These filters ensure that a ciphersuite with export-suitable or null encryption is used,
// but exclude anonymous Diffie-Hellman key change as this is vulnerable to man-in-the-middle attacks
FiltersType filters = new FiltersType();
filters.getInclude().add(".*_EXPORT_.*");
filters.getInclude().add(".*_EXPORT1024_.*");
filters.getInclude().add(".*_WITH_DES_.*");
filters.getInclude().add(".*_WITH_AES_.*");
filters.getInclude().add(".*_WITH_NULL_.*");
filters.getExclude().add(".*_DH_anon_.*");
tlsParams.setCipherSuitesFilter(filters);
httpConduit.setTlsClientParameters(tlsParams);
} catch (Exception exception) {
LOGGER.error("Security configuration failed with the following: " + exception.getCause(), exception);
}
}

IOException Error on Putting Uri Source In Media Player (setDataSource)

Getting an IOException Error While Putting Uri Source Into An Object Of MediaPlayer Using setDataSource. Trying To Get Uri Of A Song From Mobile Using
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 10);
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && requestCode == 10){
Uri uriSound=data.getData();
Toast.makeText(getApplicationContext(),"It Came Here",Toast.LENGTH_SHORT).show();
play_sound(uriSound);
}
}
play_sound
private void play_sound( Uri uri) {
Toast.makeText(getApplicationContext(),"It Came Here 2" + uri,Toast.LENGTH_LONG).show();
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(getApplicationContext(), uri);
mp.start();
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(),"Error 1",Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(),"Error 2",Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(),"Error 3",Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error 4",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
I Used Toast To Check Where Is Error .
Getting Error In "IOException e" I Dont Know What Is It On Googling It All I Get Is That It Is SOme Kind Of " File Format" Issue Of Selected File.
Solved!! By Just Adding One Line In Play Sound
mP.setAudioStreamType(AudioManager.STREAM_MUSIC);
Play_Sound(Uri uri) :
private void Play_Sound(Uri uri)
{
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(getApplicationContext(), uri);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might 1 not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might 2 not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might 3 not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might 4 not set the URI correctly!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mPlayer.start();
}

Remote Glassfish JMS lookup

I want to connect to my Glassfish Server at XX.XX.XX.XX:XXXX which is running on a ubuntu machine on our Server.
I want to send messages and then receive them.
My Receiver looks like this:
public JMS_Topic_Receiver(){
init();
}
public List<TextMessage> getCurrentMessages() { return _currentMessages; }
private void init(){
env.put("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
env.put("org.omg.CORBA.ORBInitialHost", "10.10.32.14");
env.put("org.omg.CORBA.ORBInitialPort", "8080");
try {
ctx = new InitialContext(env); // NamingException
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void subscribeTopic(String topicName, String userCredentials) {
try {
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx.lookup("myTopicConnectionFactory");
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
try {
String temp = InetAddress.getLocalHost().getHostName();
topicConnection.setClientID(temp);
} catch (UnknownHostException e) {
e.printStackTrace();
}
TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) ctx.lookup(topicName);
topicConnection.start();
TopicSubscriber topicSubscriber = topicSession.createDurableSubscriber(topic, userCredentials);
topicSubscriber.setMessageListener(new MyMessageListener());
}
catch(NamingException | JMSException ex)
{
ex.printStackTrace();
}
}
And my Sender looks like this:
public JMS_Topic_Sender(){
init();
}
private void init(){
env.put("java.naming.factory.initial","com.sun.enterprise.naming.SerialInitContextFactory");
env.put("org.omg.CORBA.ORBHost","10.10.32.14");
env.put("org.omg.CORBA.ORBPort","8080");
try {
ctx = new InitialContext(env);
} catch (NamingException e) {
e.printStackTrace();
}
}
public void sendMessage(String message, String topicName) {
try {
TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) ctx.lookup("myTopicConnectionFactory");
if (topicConnectionFactory != null) {
TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) ctx.lookup(topicName);
topicConnection.start();
TopicPublisher topicPublisher = topicSession.createPublisher(topic);
TextMessage tm = topicSession.createTextMessage(message);
topicPublisher.send(tm);
topicSession.close();
topicConnection.stop();
topicConnection.close();
}
} catch (NamingException e) {
e.printStackTrace();
} catch (JMSException e) {
e.printStackTrace();
}
}
I got most of this code from various tutorials online.
Now when I want to do the lookup aka. -> ctx.lookup("myTopicConnectionFactory");
I get all sorts of errors thrown:
INFO: HHH000397: Using ASTQueryTranslatorFactory
org.omg.CORBA.COMM_FAILURE: FEIN: 00410008: Connection abort vmcid: OMG minor code: 8 completed: Maybe
javax.naming.NamingException: Lookup failed for 'myTopicConnectionFactory' in SerialContext ........
My question here is, how do I do the lookup correctly?
My guess is that my Propertys (env) are incorrect and I need to change thouse, but I dont know to what?
Also, it works if i run my Glassfish localy on my own Computers localhost.
When im using localhost as adress and 8080 as port.

Outbound (!) SSL connection Wildfly

our Wildfly 8.1-Server needs to establish an outbound (!) LDAPS-connection to a server within the organization's network. This connection is only used to sync various application data.
Unfortunately, there's no documentation about Wildfly's outbound-only truststore. Every research I do just gives me results about enabling SSL for inbound connections.
How exactly can I add a certificate to Wildfly's truststore for outbound SSL connections? Is there any documentation about this? I'd be thankful for any help on this topic.
Found two possible solutions. First the one i would not use:
System.setProperty("javax.net.ssl.trustStore",path_to_your_cacerts_file);
The second one I'd prefer:
public class LDAPSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory actualSocketFactory;
public LDAPSSocketFactory() {
InputStream certificateInputStream = this.getClass().getClassLoader().getResourceAsStream("yourcert.pfx");
try {
KeyStore pkcs12 = KeyStore.getInstance("pkcs12");
pkcs12.load(certificateInputStream, "".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(pkcs12);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
actualSocketFactory = ctx.getSocketFactory();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
//Override methods by simply deligating them to the actualSocketFactory
}
And pass this as an JNDI param for ldap connections:
env.put("java.naming.ldap.factory.socket", "LDAPSSocketFactory");
Found all of this on StackOverflow, but I forgot where exactly, so I basically pasted their solution here.

javax.net.ssl.sslpeerunverifiedexception no peer certificate Error In lifelogApi

We are getting SSL peer unverified error while fetching the access token from Lifelog api. I am able to get the authcode, but when i am trying to get access token, it is giving me SSL peer error. It works fine with few device, but most of the device it is giving SSL error.
private void getAccessToken(final String authCode)
{
final String finalUrl = String.format("https://platform.lifelog.sonymobile.com/oauth/2/token?client_id=%s&client_secret=%s&code=%s",CLIENT_ID,CLIENT_SECRET,authCode);
Thread networkThread = new Thread(new Runnable() {
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(finalUrl);
// Add your data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("client_id", CLIENT_ID));
nameValuePairs.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
nameValuePairs.add(new BasicNameValuePair("code", authCode));
AbstractHttpEntity ent=new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
post.setEntity(ent);
// Execute HTTP Post Request
HttpResponse response =null;
try {
response = client.execute(post);
Log.d("Response:" , response.toString());
} catch (IOException e) {
e.printStackTrace();
}
String dataObject = response.toString();
JSONObject obj;
if(dataObject != null) {
obj = null;
try {
String json_string = EntityUtils.toString(response.getEntity());
// displayToast(json_string);
obj = new JSONObject(json_string);
SharedPreferences prefs =getSharedPreferences("Myprefs", Context.MODE_PRIVATE);
prefs.edit().putString("Access_token", obj.getString("access_token"));
// prefs.edit().putString(AUTH_REFRESH_TOKEN, obj.getString(AUTH_REFRESH_TOKEN));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
});
networkThread.start(); }
The problem may be with your use of HttpClient. It looks like Google has removed support for this call in Android 6.0.
http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client
You should be able to use HttpsURLConnection instead of Httpclient to access the Lifelog Web Service.
I'm using google-oauth-client, I was able to use on Android 5.x with this initialization for
import com.google.api.client.http.HttpTransport;
private void initializeSocketFactory() {
if (Build.VERSION.SDK_INT >= 23) {
HTTP_TRANSPORT = new NetHttpTransport();
} else {
//Android 5 and bellow needs this SSL Socket factory initialization
try {
SSLContext sslContext = SSLContext.getInstance("TLSv1");
sslContext.init(null, null, null);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
NetHttpTransport.Builder netTransportBuilder = new NetHttpTransport.Builder();
netTransportBuilder.setSslSocketFactory(socketFactory);
HTTP_TRANSPORT = netTransportBuilder.build();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
Log.e(LOG_TAG, "Problem instantiating cipher for ssl socket", e);
}
}
}
You use HTTP_TRANSPORT to instantiate:
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;