Skip to content

Instantly share code, notes, and snippets.

@ohall
Created June 25, 2024 12:52
Show Gist options
  • Save ohall/e602a8cb696e26ff21fbc09ba2eb2f0b to your computer and use it in GitHub Desktop.
Save ohall/e602a8cb696e26ff21fbc09ba2eb2f0b to your computer and use it in GitHub Desktop.
Adding a self signed cert to Java KeyStore
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
public class TrustSelfSignedCert {
  public static void main(String[] args) throws Exception {
  FileInputStream is = new FileInputStream("path/to/self-signed-cert.crt");
  // Create a KeyStore containing our trusted CAs
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, null);
  ks.setCertificateEntry("selfsigned", CertificateFactory.getInstance("X.509").generateCertificate(is));
  // Create a TrustManager that trusts the CAs in our KeyStore
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(ks);
  // Create an SSLContext that uses our TrustManager
  SSLContext ctx = SSLContext.getInstance("TLS");
  ctx.init(null, tmf.getTrustManagers(), null);
  SSLSocketFactory ssf = ctx.getSocketFactory();
  SSLSocket s = (SSLSocket) ssf.createSocket("example.com", 443);
  s.startHandshake();
  System.out.println("Connection established");
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment