Skip to content

Instantly share code, notes, and snippets.

@ato
Created June 1, 2012 15:57
Show Gist options
  • Save ato/2853159 to your computer and use it in GitHub Desktop.
Save ato/2853159 to your computer and use it in GitHub Desktop.
Bundling CA certs
(ns leiningen.core.ssl
(:require [clojure.java.io :as io])
(:import java.security.KeyStore
java.security.KeyStore$TrustedCertificateEntry
java.security.cert.CertificateFactory
javax.net.ssl.SSLContext
javax.net.ssl.TrustManagerFactory
javax.net.ssl.X509TrustManager))
(defn ^TrustManagerFactory trust-manager-factory [^KeyStore keystore]
(doto (TrustManagerFactory/getInstance "PKIX")
(.init keystore)))
(defn default-trust-managers []
(let [tmf (trust-manager-factory nil)
tms (.getTrustManagers tmf)]
(filter #(instance? X509TrustManager %) tms)))
(defn default-trusted-certs
"Lists the CA certificates trusted by the JVM."
[]
(mapcat #(.getAcceptedIssuers %) (default-trust-managers)))
(defn read-certs
"Read one or more X.509 certificates in DER or PEM format."
[f]
(let [cf (CertificateFactory/getInstance "X.509")]
(.generateCertificates cf (io/input-stream f))))
(defn make-keystore
"Construct a KeyStore that trusts a collection of certificates."
[certs]
(let [ks (KeyStore/getInstance "jks")]
(.load ks nil nil)
(doseq [[i cert] (map vector (range) certs)]
(.setEntry ks (str i) (KeyStore$TrustedCertificateEntry. cert) nil))
ks))
(defn make-sslcontext
"Construct an SSLContext that trusts a collection of certificatess."
[trusted-certs]
(let [ks (make-keystore trusted-certs)
tmf (trust-manager-factory ks)]
(doto (SSLContext/getInstance "TLS")
(.init nil (.getTrustManagers tmf) nil))))
(defn add-ca-certs
"Replaces the default SSLContext with one that additional trusts the
given certs."
[certs]
(let [certs (into (default-trusted-certs) certs)]
(SSLContext/setDefault (make-sslcontext certs))))
(comment
(add-ca-certs (read-certs (io/resource "ca.pem")))
(.openStream (java.net.URL. "https://clojars.org/"))
;; => #<HttpInputStream ...>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment