Skip to content

Instantly share code, notes, and snippets.

@vigevenoj
Last active March 20, 2021 05:32
Show Gist options
  • Save vigevenoj/91f5eb3cb485386000c0742a0c3a5ce8 to your computer and use it in GitHub Desktop.
Save vigevenoj/91f5eb3cb485386000c0742a0c3a5ce8 to your computer and use it in GitHub Desktop.
have a cert? need a socket factory with that cert as a trusted root? this does that.
(ns church.buttstuff.certs
(:require
[clojure.java.io :as io]
(:import
(java.security Keystore)
(java.security.cert CertificateFactory)
(javax.net.ssl SSLContext)
(javax.net.ssl TrustManagerFactory)))
(defn use-custom-ssl?
[]
; we use a cprop env here, but you could use any way of supplying this path
(not (nil? (env :ca-cert-path))))
(defn socket-factory-from-ca-cert-path
"Returns a socket factory with the provided certificate loaded as the only trust root."
[filepath]
(when (use-custom-ssl?)
(let [ca-certificate (.generateCertificate
(CertificateFactory/getInstance "X.509")
(clojure.java.io/input-stream filepath))
ca-keystore (KeyStore/getInstance (KeyStore/getDefaultType))
tmf (TrustManagerFactory/getInstance "X509")
ssl-context (SSLContext/getInstance "TLSv1.2")]
(do
(.load ca-keystore nil (char-array ""))
(.setCertificateEntry ca-keystore "ca-certificate" ca-certificate)
(.init tmf ca-keystore)
(.init ssl-context nil (.getTrustManagers tmf) nil)
(.getSocketFactory ssl-context)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment