Created
June 25, 2024 12:52
-
-
Save ohall/e602a8cb696e26ff21fbc09ba2eb2f0b to your computer and use it in GitHub Desktop.
Adding a self signed cert to Java KeyStore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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