package
com.demo.ssl;
import
java.io.FileInputStream;
import
java.io.InputStream;
import
java.io.OutputStream;
import
java.security.KeyStore;
import
javax.net.ssl.KeyManagerFactory;
import
javax.net.ssl.SSLContext;
import
javax.net.ssl.SSLSocket;
import
javax.net.ssl.TrustManagerFactory;
public
class
SSLClient {
private
SSLSocket sslSocket;
public
static
void
main(String[] args)
throws
Exception {
SSLClient client =
new
SSLClient();
client.init();
System.out.println(
"SSLClient initialized."
);
client.process();
}
public
void
init()
throws
Exception {
String host =
"127.0.0.1"
;
int
port =
1234
;
String keystorePath =
"/home/user/CA/certs/client.keystore"
;
String trustKeystorePath =
"/home/user/CA/certs/ca-trust.keystore"
;
String keystorePassword =
"abc123_"
;
SSLContext context = SSLContext.getInstance(
"SSL"
);
KeyStore clientKeystore = KeyStore.getInstance(
"pkcs12"
);
FileInputStream keystoreFis =
new
FileInputStream(keystorePath);
clientKeystore.load(keystoreFis, keystorePassword.toCharArray());
KeyStore trustKeystore = KeyStore.getInstance(
"jks"
);
FileInputStream trustKeystoreFis =
new
FileInputStream(trustKeystorePath);
trustKeystore.load(trustKeystoreFis, keystorePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
"sunx509"
);
kmf.init(clientKeystore, keystorePassword.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
"sunx509"
);
tmf.init(trustKeystore);
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(),
null
);
sslSocket = (SSLSocket)context.getSocketFactory().createSocket(host, port);
}
public
void
process()
throws
Exception {
String hello =
"hello boy!"
;
OutputStream out = sslSocket.getOutputStream();
out.write(hello.getBytes(),
0
, hello.getBytes().length);
out.flush();
InputStream in = sslSocket.getInputStream();
byte
[] buffer =
new
byte
[
50
];
in.read(buffer);
System.out.println(
new
String(buffer));
}
}