Update Ciphers list in JAVA windows - java

I need to send a secured request using java(jre1.8.0_65) on my Windows,
I used the below code to configure my certs and key factory.
KeyStore ks = KeyStore.getInstance("PKCS12");
//FileInputStream fis = new FileInputStream("certs/tester1024.pfx");
InputStream ins = this.getClass().getClassLoader()
.getResourceAsStream("certs/tester1024.pfx");
ks.load(ins, "1234".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SUNX509");
kmf.init(ks, "1234".toCharArray());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), null, null);
URL obj = new URL(httpURL);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection)connection)
.setSSLSocketFactory(sc.getSocketFactory());
}
connection.setRequestMethod(method);
responseCode = connection.getResponseCode();
the above code works but the list of Ciphers sent Client in the "CLIENT HELLO" does not include the Cipher TLS_RSA_WITH_AES_256_CBC_SHA256.
it includes this TLS_RSA_WITH_AES_128_CBC_SHA256
In the Client Hello Ciper list, I want this Cipherto be included.
Please let me do I need to update any thing related to JAVA on windows, because on linux same java application includes both the Ciphers.

Related

SSL exceptions with existing certfiicates

Below is our code snippet to connect to a third party using SSL. Most of the solutions I found at SOF are for importing the certs to truststore, which I belive I am already doing as part of the below code. Nothing had changed and the certificate is still valid.
I had this code working until last week and now I am receving the below SSLHandShakeException. Any clues on what might have went wrong would be greatly appreciated.
javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target
System.setProperties(newprops);
URL url = new URL(getURL());
File inFile = new File(FileLocation);
String path = inFile.getAbsolutePath();
System.out.print("Absolute Pathname "+ path);
KeyStore clientStore = KeyStore.getInstance("PKCS12");
clientStore.load(new FileInputStream(path), Password.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientStore, Password.toCharArray());
KeyManager[] kms = kmf.getKeyManagers();
SSLContext sslContext = null;
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kms, null, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
System.out.print("connection "+ connection);
//URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setConnectTimeout(getConnectionTimeout());
connection.setReadTimeout(getReadTimeout());
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonObjectStr.toString());
System.out.println("OutputStreamWriter : > " + out.toString());
out.close();

java establish sslsocket use .cer file

I am new to Java and SSLSocket. I want to use a specified .cer file to establish a SSLSocket in client part. I search it in google, but doesn't find good solution to it. And here is my code:
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(new FileInputStream("myCer.cer"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} 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);
SSLSocket sock = (SSLSocket)context.getSocketFactory().createSocket("...",21000); //"...": here I ignore the host name. The address and port is right.
sock.setUseClientMode(true);
if(sock.isConnected()) {
System.out.println("Connected...");
}
else
{
System.out.println("Connect Fails...");
}
Login.pbLogin login = Login.pbLogin.newBuilder().setUserID("dbs")
.setPassword("abcd1234")
.setNewPassword("")
.setClientVersion("1.0.0.0")
.setRestarted(true)
.build();
OutputStream outputStream =sock.getOutputStream();
byte[] b1=login.getClass().getSimpleName().getBytes("UTF-8");
byte[] b2=login.toByteArray();
byte[] bytes = ByteBuffer.allocate(4).putInt(b1.length + b2.length).array();
outputStream.write(bytes);
outputStream.write(b1); //login.getClass().getSimpleName().getBytes("UTF-8")
outputStream.write(b2); //login.toByteArray()
outputStream.flush();
byte[] content = new byte[100];
int bytesRead = -1;
InputStream inputStream = sock.getInputStream();
String str;
while(( bytesRead = inputStream.read( content) ) != -1){
System.out.println("OK ,receive.....");
// str = new String(Arrays.copyOfRange(content,0,bytesRead), StandardCharsets.UTF_8);
//System.out.println(str);
}
I use TCPViewer to see, the SSLSocket is in Established state, but when executing outstream.write , the SSLsocket will be Close_wait state and cause exception:
Exception in thread "main" java.net.SocketException: Software caused connection abort: socket write error.
So I couldn't write the info to server, and exit program. I guess the SSLSocket is not established successfully, but Tcpviewer show it is established early, and it's in Connected state(print "connected."). But when try to write the outputstream, it will in Close_wait state. Could you help me to sort it out?
Then I found the reason today. The code has no issue, the reason is that server part can't parse the protocol buffer (pblogin) correctly, which causes exception, so it close the socket. As a result , the state will be in close_wait.Since I find the reason , wish I can solve it by myself.

SSL server socket and handshake with known certificate

I am new to SSl server sockets. All I am tying to do is to read data over SSL.
My application listens on port 8000. Please give me few steps on how I can do this. When I have a certificate (on my disc), how can I establish the SSL server socket and read from client ?
Here are my steps
1) reading server.crt from file and making X509Certificate (has public certificate and private key)
2) Getting instance of JKS keystore
3) Get instance of context
4) create server socket over the port (8000)
InputStream in = new DataInputStream(new FileInputStream(new File("server.crt")));
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
in.close();
ks.setCertificateEntry("dts", cert);
char[] newpass = "password".toCharArray();
String name = "mykeystore.ks";
FileOutputStream output = new FileOutputStream(name);
ks.store(output, newpass);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, "password".toCharArray());
try{
System.setProperty("javax.net.ssl.keyStore","mykeystore.ks");
System.setProperty("javax.net.ssl.keyStorePassword","password");
System.setProperty("javax.net.debug","all");
SSLContext context = SSLContext.getInstance("TLSv1.2");
context.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory sslServerSocketfactory = context.getServerSocketFactory();
SSLServerSocket sslServerSocket = (SSLServerSocket)sslServerSocketfactory.createServerSocket(8000);
SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept();
InputStream dataIN = sslSocket.getInputStream();
byte[] hello = new byte[20];
dataIN.read(hello);
System.out.println(new String(hello));
dataIN.close();
} catch (IOException e){
e.printStackTrace();
}
I got the answer for my question, I did research on how to setup my own keystore with self signed certificate. This way helped me.
ping me for a detailed solutions.

Apple push APNS connection

I am trying to connect to Apple's push notification server to send down notifications but I am having some issues connecting. After I attempt the handshake, it shows that says that I am not connected. I am not getting any exceptions? It isn't a issue with my certificate because I tried using 3rd party libraries with the certificate and I was able to push with no problem.
int port = 2195;
String hostname = "gateway.sandbox.push.apple.com";
char[] passwKey = "password".toCharArray();
KeyStore ts = KeyStore.getInstance("PKCS12");
ts.load(new FileInputStream("/path/to/file/Cert.p12"), passwKey);
KeyManagerFactory tmf = KeyManagerFactory.getInstance("SunX509");
tmf.init(ts, passwKey);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(tmf.getKeyManagers(), null, null);
SSLSocketFactory factory = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket(hostname,port);
String[] suites = socket.getSupportedCipherSuites();
socket.setEnabledCipherSuites(suites);
//start handshake
socket.startHandshake();
//THIS ALWAYS RETURNS FALSE
boolean connected = socket.isConnected();
This always returns false, but I was able to communicate with no problems.
boolean connected = socket.isConnected();

Where to place SSL certificate for java application

Hello all
I want to generate a certificate using keystore than add this to my sevrer and browse my sever using IE. I need the steps for generating the certificate in plain english as all what i read in the internet is hard to be understod. The server socket is:
SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
SSLServerSocket Server = (SSLServerSocket)ssf.createServerSocket(1234);
String[] cipher = {"SSL_DH_anon_WITH_RC4_128_MD5"};
Server.setEnabledCipherSuites(cipher);
The certificate code is this but not sure where to pu it in my server:
InputStream infil = new FileInputStream("server.cer");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(infil);
infil.close();
KeyStore ks = null;
ks = KeyStore.getInstance("JKS", "SUN");
InputStream is = null;
is = new FileInputStream(new File("./keystore"));
ks.load(is,"rootroot".toCharArray());
See the Javadoc/Security/JSSE Reference.

Categories