0

How would I go about making a socket connection between two java SE applications where the key is not from a trusted store or certificate but instead is hardcoded in the application itself.

e.g. public key hardcoded on the clients and private key on the server. How would I go about doing it while still using the standard TLS/SSL socket api?

Allahjane
  • 1,920
  • 3
  • 24
  • 42

2 Answers2

0

You Can Generate a JKS(Java Key Store) from the Certificate and Key files, and import it in your JRE.

You can use keytool for generating JKS and importing it into Keystore.

Use the command: keytool -import -alias <Your Alias> -file CertificateFile.cer -keystore <currentKeyStore>

By Default, your currentKeyStore would be at: JAVA_HOME-> JRE ->lib-> security-> cacerts

Sandeep Kaul
  • 2,957
  • 2
  • 20
  • 36
0

Generate self-signed certificate, private key goes to server, certificate with public key goes to client. After that you need properly set up SSLContext on client side. This can be achieve basically in 3 way.

1 - add server certificate CA (for self-signed CA == certificate) into client $JRE/lib/security/cacerts file. That not very good, because after JRE update on client you can lost this changes.

2 - put server certificate into keystore and set up environment variables (with System.setProperty or as -D command line option) javax.net.ssl.trustStore, javax.net.ssl.trustStorePassword and, optionally, javax.net.ssl.trustStoreType, check this answer for details https://stackoverflow.com/a/5871352/1516873

3 - Manual set up SSLContext trustStoreManager, for example:

private final SSLContext createSSLContext()
        throws Exception {

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream("path to server certificate.pem"); // server certificate in PEM format
    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(null);
    try {
        X509Certificate cacert = (X509Certificate) cf.generateCertificate(in);
        trustStore.setCertificateEntry("server_alias", cacert);
    } finally {
        IOUtils.closeQuietly(in);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(trustStore);

    SSLContext sslContext = SSLContext.getInstance("SSL"); // TLS e.g.
    sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
    return sslContext;
}
Community
  • 1
  • 1
user1516873
  • 5,060
  • 2
  • 37
  • 56