Skip to content

Instantly share code, notes, and snippets.

@joshuakfarrar
Last active September 24, 2023 07:13
Show Gist options
  • Save joshuakfarrar/d6fc1f350e9fb8eb50b6290ada4afc53 to your computer and use it in GitHub Desktop.
Save joshuakfarrar/d6fc1f350e9fb8eb50b6290ada4afc53 to your computer and use it in GitHub Desktop.
(ns key-generator.core
(:import (java.security KeyPairGenerator Key)
(java.util Base64)))
(def ^:private algorithm->key-type
{:RS256 "RSA"
:ES256 "EC"})
(def ^:private algorithm->key-size
{:RS256 512
:ES256 256})
(defn generate-key-pair
"Generates a private/public key pair based on the specified cryptographic algorithm."
[alg & {:keys [key-size]}]
(let [alg-keyword (if (string? alg)
(keyword alg)
alg)
key-size-final (or key-size
(algorithm->key-size alg-keyword))
generator (doto (->> alg-keyword
(get algorithm->key-type)
(KeyPairGenerator/getInstance))
(.initialize key-size-final))
key-pair (.generateKeyPair generator)]
{:private-key (.getPrivate key-pair)
:public-key (.getPublic key-pair)}))
(defn- key->pem [^Key key]
(let [header (if (= (.getFormat key) "X.509") "-----BEGIN PUBLIC KEY-----\n" "-----BEGIN PRIVATE KEY-----\n")
footer (if (= (.getFormat key) "X.509") "\n-----END PUBLIC KEY-----" "\n-----END PRIVATE KEY-----")
encoder (Base64/getMimeEncoder 64 (.getBytes "\n" "UTF-8"))
encoded-key (.encodeToString encoder (.getEncoded key))]
(str header encoded-key footer)))
(defn write-key-to-disk [filename key]
(with-open [writer (clojure.java.io/writer filename)]
(.write writer (key->pem key))))
(defn -main [& args]
(let [[alg output-dir] args
{key-size :key-size} (apply hash-map (drop 2 args))
key-pair (generate-key-pair alg {:key-size key-size})]
(write-key-to-disk (str output-dir "/private-key.txt") (:private-key key-pair))
(write-key-to-disk (str output-dir "/public-key.txt") (:public-key key-pair))))
(defproject key-generator "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
:url "https://www.eclipse.org/legal/epl-2.0/"}
:dependencies [[org.clojure/clojure "1.11.1"]]
:repl-options {:init-ns key-generator.core}
:main ^:skip-aot key-generator.core)
@joshuakfarrar
Copy link
Author

openssl rsa -in .\private-key.txt -check
openssl rsa -pubin -in .\public-key.txt -text

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment