Created
July 12, 2024 12:01
-
-
Save henryw374/609d2ee368b10d5f5c05e28ba7fb0492 to your computer and use it in GitHub Desktop.
Import PKCS12 certificate chain directly in clojure
This file contains 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
(ns webserver-ssl-context | |
(:require [clojure.java.io :as io] | |
[clojure.string :as str] | |
) | |
(:import (java.security KeyFactory KeyStore) | |
(java.security.spec X509EncodedKeySpec) | |
[javax.xml.bind DatatypeConverter])) | |
(defn parse-der-from-pem [pem begin-delimiter end-delimiter] | |
(let [data (str/join (rest (str/split (String. pem) begin-delimiter))) | |
tokens (str/split data end-delimiter) | |
ders (mapv #(DatatypeConverter/parseBase64Binary %) tokens)] | |
(into-array ders))) | |
(defn generate-private-key-from-der [key-bytes] | |
(let [spec (X509EncodedKeySpec. key-bytes) | |
factory (KeyFactory/getInstance "RSA")] | |
(.generatePrivate factory spec))) | |
(defn generate-certificate-from-der [cert-bytes] | |
(let [factory (java.security.cert.CertificateFactory/getInstance "X.509")] | |
(.generateCertificate factory (java.io.ByteArrayInputStream. cert-bytes)))) | |
(defn create-ssl-context-factory [cert-file private-key-file] | |
(try | |
(let [cert-bytes (parse-der-from-pem (slurp cert-file) "-----BEGIN CERTIFICATE-----" "-----END CERTIFICATE-----") | |
key-bytes (parse-der-from-pem (slurp private-key-file) "-----BEGIN PRIVATE KEY-----" "-----END PRIVATE KEY-----") | |
x-certs (mapv generate-certificate-from-der cert-bytes) | |
key (generate-private-key-from-der (first key-bytes)) | |
keystore (doto (KeyStore/getInstance "PKCS12") | |
(.load nil) | |
(.setCertificateEntry "cert-alias" (first x-certs)) | |
(.setKeyEntry "key-alias" key (char-array "temp-pw") (into-array x-certs))) | |
ssl-context-factory (doto (org.eclipse.jetty.util.ssl.SslContextFactory$Server.) | |
(.setKeyStore keystore) | |
(.setKeyStorePassword "temp-pw"))] | |
ssl-context-factory) | |
(catch Exception e | |
(throw (IllegalArgumentException. e))))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment