Can any one please explain the below code (labeled "HERE").
Keystore.load() performs what?
Why KeyManagerFactory is used?
I need practical oriented solution.
System.setProperty("1", "/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre");
String jrehome = System.getProperty("1");
String path = jrehome + "/" + "lib" + "/" + "security" + "/" + "cacerts";
char[] ksPass= "changeit".toCharArray();
try {
KeyStore ks = KeyStore.getInstance("JKS"); // <- HERE
System.out.println(ks.toString());
ks.load(new FileInputStream(path), ksPass);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, ksPass);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
System.out.println(ks.getCertificate("SunX509"));
tmf.init(ks);
SSLContext sc = SSLContext.getInstance("TLS");
sc.getClientSessionContext().setSessionCacheSize(1);
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLServerSocketFactory ssf = sc.getServerSocketFactory();
SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(8888); // <-- HERE
System.out.println("Server started:");
}
Keystore.load() is a mandatory call for accessing a keystore else you cannot acces it. The Javadoc says so. Once the keystore has been loaded, it is possible to read existing entries from the keystore, or to write new entries into the keystore. You have some overloaded method for load().
KeyManagerFactory is a class that follows Factory pattern which creates Key Manager instances for managing a specific type of key material for use by secure sockets.
Related
I want to calculate the time which the ssl(client) needs to establish a connection with a server and make the Handshake. Here is my code and it works fine.
private boolean SslTlsConnection() throws IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, UnrecoverableKeyException, KeyManagementException {
KeyStore client = KeyStore.getInstance("JKS");
client.load(new FileInputStream(currentPath + "clientcert.keystore"), Password.toCharArray());
KeyStore trust = KeyStore.getInstance("JKS");
trust.load(new FileInputStream(currentPath + "myTrustStore.keystore"), Password.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(client, Password.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trust);
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustManagers = tmf.getTrustManagers();
sc.init(kmf.getKeyManagers(), trustManagers, new java.security.SecureRandom());
SSLSocketFactory ssf = sc.getSocketFactory();
sslsocket = (SSLSocket) ssf.createSocket(Properties.host, Properties.portNumber);
sslsocket.startHandshake();
System.out.println("Handshaking Complete");
System.out.println("Just connected to " + sslsocket.getInetAddress() + "\n");
transport = new IOTransport(sslsocket);
return false;
}
private void close(){
sslsocket.close();
}
I am just curious about the performance. I run multiple connections in a loop and i am calculating the time ssl needs to do the handshake. My question is why the first time which client connect with ssl take so long time in compare with others. Did i something wrong?
for (int i = 1; i < loopvalue; i++) {
long elapseTime = System.currentTimeMillis();
SslTlsConnection()
long elapseTime = (System.currentTimeMillis() - elapseTime);
close();
}
I've tried tests . Here are the results
SSL_Execution_Time
First Execution Time 453ms
Second Execution Time 85ms
Third Execution Time 90ms
The initial ssl handshake only takes place once. The client and server agree on the protocol (ssl vs tls) and the cyphers and they exchange the keys. So a hit is taken on the initial handshake. After that the only thing that happens is the encryption and decryption using the already exchanged keys.
http://www.ibm.com/support/knowledgecenter/SSFKSJ_7.1.0/com.ibm.mq.doc/sy10660_.htm
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.
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.
I'm trying to skin this cat: Use PEM Encoded CA Cert on filesystem directly for HTTPS request? another way.
Java has a class KeyStore.TrustedCertificateEntry, but I can't figure out how to load a certificate into it. My code looks similar to below:
import java.security.KeyStore.TrustedCertificateEntry;
...
X509Certificate ca = (X509Certificate) CertificateFactory(...);
KeyStore ks = TrustedCertificateEntry(ca);
And:
X509Certificate ca = (X509Certificate) CertificateFactory(...);
KeyStore ks = KeyStore.TrustedCertificateEntry(ca);
And:
X509Certificate ca = (X509Certificate) CertificateFactory(...);
KeyStore ks = new KeyStore.TrustedCertificateEntry(ca);
And:
X509Certificate ca = (X509Certificate) CertificateFactory(...);
KeyStore ks = new KeyStore.TrustedCertificateEntry(ca);
The program fails to compile with errors similar to:
SuperCert.java:33: error: cannot find symbol
KeyStore ks = TrustedCertificateEntry(ca);
^
symbol: method TrustedCertificateEntry(X509Certificate)
location: class TestCert
After loading my X509 cert into the KeyStore, I plan on using it in a TrustManagerFactory and ultimately fetching a web page with HttpsURLConnection.
How does one load a X509Certificate into a TrustedCertificateEntry?
I found it based on Vit Hnilica's answer at loading a certificate from keystore. I"m going to leave the question with this answer since most Stack Overflow answers start with "convert with openssl, then use keytool ...".
Hat's off to Vit for posting that answer. Hnilica's answer is the only one I found after wading through pages of similar questions and answers on Stack Overflow.
String CA_FILE = ...;
FileInputStream fis = new FileInputStream(CA_FILE);
X509Certificate ca = (X509Certificate) CertificateFactory.getInstance(
"X.509").generateCertificate(new BufferedInputStream(fis));
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setCertificateEntry(Integer.toString(1), ca);
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
There is also another approach.
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(file));
keyStore.setEntry(alias, new KeyStore.TrustedCertificateEntry(certificate), null);
ProtectionParameter for TrustedCertificateEntry should be null.
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();