├── .github └── workflows │ └── clojure.yml ├── .gitignore ├── LICENSE ├── README.md ├── cljdoc-lein-preview.sh ├── project.clj ├── src └── clj_ssh_keygen │ ├── core.clj │ ├── oid.clj │ └── utils.clj └── test └── clj_ssh_keygen └── core_test.clj /.github/workflows/clojure.yml: -------------------------------------------------------------------------------- 1 | name: Clojure CI 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v3 16 | - name: Install dependencies 17 | run: lein deps 18 | - name: Run tests 19 | run: lein test 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.pub 3 | *.pem 4 | profiles.clj 5 | pom.xml 6 | pom.xml.asc 7 | *.jar 8 | *.class 9 | /.lein-* 10 | /.nrepl-port 11 | /lib/ 12 | /classes/ 13 | /target/ 14 | /checkouts/ 15 | .lein-deps-sum 16 | .lein-repl-history 17 | .lein-plugins/ 18 | .lein-failures 19 | .cpcache/ 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020-2024 Saidone 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # clj-ssh-keygen 2 | 3 | [![Clojars Project](https://img.shields.io/clojars/v/clj-ssh-keygen.svg)](https://clojars.org/clj-ssh-keygen) 4 | [![cljdoc badge](https://cljdoc.org/badge/clj-ssh-keygen/clj-ssh-keygen)](https://cljdoc.org/d/clj-ssh-keygen/clj-ssh-keygen) 5 | 6 | Generate RSA PKCS #1 keys **from scratch** and **without 3rd party libs** in Clojure, export **PEM** and **OpenSSH** formats 7 | 8 | *☛ intended for hacking and educational purposes only!* 9 | 10 | ![public key](https://i.postimg.cc/HLhvSkpk/pubkey.png) 11 | 12 | ## Usage 13 | ```clojure 14 | (let [key (generate-key)] 15 | (write-private-key! key "pvt.pem") 16 | (write-public-key! key "pub.pem") 17 | (write-openssh-public-key! key "id_rsa.pub"))) 18 | ``` 19 | for generating a default (2048 bit) length key, while: 20 | ```clojure 21 | (write-private-key! (generate-key 2345) "pvt.pem") 22 | ``` 23 | will issue a custom length key: 24 | ```console 25 | $ openssl rsa -noout -text -in pvt.pem|head -n 1 26 | RSA Private-Key: (2345 bit, 2 primes) 27 | ``` 28 | 29 | ## License 30 | Copyright (c) 2020-2024 Saidone 31 | 32 | Distributed under the MIT License 33 | -------------------------------------------------------------------------------- /cljdoc-lein-preview.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # get project name 4 | PROJECT=$(cat project.clj | grep defproject | cut -d " " -f 2 | cut -d "/" -f 2) 5 | # get group id 6 | GROUP_ID=$(cat project.clj | grep defproject | cut -d " " -f 2 | cut -d "/" -f 1) 7 | # get version 8 | VERSION=$(cat project.clj | grep defproject | cut -d " " -f 3 | tr -d '"') 9 | 10 | echo "Generating cljdoc for $PROJECT-$VERSION" 11 | 12 | # clean up previous run 13 | sudo rm -rf /tmp/cljdoc 14 | mkdir -p /tmp/cljdoc 15 | 16 | # build and install into local repo 17 | echo "Installing $PROJECT-$VERSION jar and pom into local repo" 18 | lein install 19 | 20 | # ingest into cljdoc 21 | docker run --rm \ 22 | -v $(pwd):/$PROJECT \ 23 | -v $HOME/.m2:/root/.m2 \ 24 | -v /tmp/cljdoc:/app/data \ 25 | --entrypoint clojure \ 26 | cljdoc/cljdoc -Sforce -M:cli ingest \ 27 | --project $GROUP_ID/$PROJECT \ 28 | --version $VERSION \ 29 | --git /$PROJECT \ 30 | 31 | # start server 32 | docker run --rm -p 8000:8000 -v /tmp/cljdoc:/app/data -v $HOME/.m2:/root/.m2 cljdoc/cljdoc 33 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject clj-ssh-keygen "0.2.5-SNAPSHOT" 2 | :description "Generate RSA PKCS #1 key-pairs from scratch in Clojure" 3 | :url "https://github.com/saidone75/clj-ssh-keygen" 4 | :license {:name "MIT" 5 | :url "https://github.com/saidone75/clj-ssh-keygen/blob/master/LICENSE"} 6 | :dependencies [[org.clojure/clojure "1.11.3"]] 7 | :main ^:skip-aot clj-ssh-keygen.core 8 | :target-path "target/%s" 9 | :profiles {:uberjar {:aot :all}}) 10 | -------------------------------------------------------------------------------- /src/clj_ssh_keygen/core.clj: -------------------------------------------------------------------------------- 1 | ;; Copyright (c) 2020-2024 Saidone 2 | 3 | (ns clj-ssh-keygen.core 4 | (:import [java.security SecureRandom]) 5 | (:gen-class)) 6 | 7 | (require '[clj-ssh-keygen.utils :as utils] 8 | '[clj-ssh-keygen.oid :as oid]) 9 | 10 | ;; (minimum) key length 11 | (def ^:private key-length 2048) 12 | 13 | ;; public exponent 14 | (def ^:private e (biginteger 65537)) 15 | 16 | ;; generate a prime number of (key length / 2) bits 17 | (defn- genprime [kl] 18 | (loop [n (BigInteger/probablePrime (quot kl 2) (SecureRandom.))] 19 | (if-not (= 1 (.mod n e)) 20 | n 21 | (recur (BigInteger/probablePrime (quot kl 2) (SecureRandom.)))))) 22 | 23 | ;; key as a quintuplet (e, p, q, n, d) 24 | (defn generate-key 25 | "Generate a PKCS #1 key of a given `kl` length (in bits, default to 2048 if not specified). 26 | The key is returned as a map meant to be used with [[public-key]], [[openssh-public-key]] or [[private-key]] functions.\\ 27 | See https://www.di-mgt.com.au/rsa_alg.html#keygen for algorithm insights." 28 | [& [kl]] 29 | (let [kl (if (< (or kl key-length) key-length) key-length (or kl key-length)) 30 | ;; public exponent 31 | e e 32 | ;; secret prime 1 33 | p (genprime kl) 34 | ;; secret prime 2 35 | ;; making sure that p x q (modulus) is exactly "kl" bit long 36 | q (loop [q (genprime kl)] 37 | (if (= kl (.bitLength (.multiply p q))) 38 | q 39 | (recur (genprime (if (odd? kl) (inc kl) kl))))) 40 | ;; modulus 41 | n (.multiply p q) 42 | ;; private exponent 43 | d (.modInverse e (.multiply 44 | (.subtract p (biginteger 1)) 45 | (.subtract q (biginteger 1))))] 46 | {:e e :p p :q q :n n :d d})) 47 | 48 | ;; ASN.1 encoding stuff 49 | ;; 50 | ;; the bare minimum for working with PKCS #1 keys 51 | ;; http://luca.ntop.org/Teaching/Appunti/asn1.html 52 | ;; 53 | ;; compute length of ASN.1 content 54 | (defn- asn1-length [c] 55 | (let [c (count c)] 56 | (cond 57 | (< c 128) [(unchecked-byte c)] 58 | (and (> c 127) (< c 256)) (concat [(unchecked-byte 0x81)] [(unchecked-byte c)]) 59 | :else (concat [(unchecked-byte 0x82)] (.toByteArray (biginteger c)))))) 60 | 61 | ;; ASN.1 generic encoding 62 | (defn- asn1-enc [tag content] 63 | (byte-array 64 | (concat 65 | [(unchecked-byte tag)] 66 | (asn1-length content) 67 | content))) 68 | 69 | ;; ASN.1 encoding for INTEGER 70 | (defn- asn1-int [n] 71 | (asn1-enc 0x02 (.toByteArray n))) 72 | 73 | ;; ASN.1 encoding for SEQUENCE 74 | (defn- asn1-seq [n] 75 | (asn1-enc 0x30 n)) 76 | 77 | ;; ASN.1 encoding for OBJECT 78 | (defn- asn1-obj [n] 79 | (asn1-enc 0x06 n)) 80 | 81 | ;; ASN.1 encoding for NULL 82 | (defn- asn1-null [] 83 | (concat 84 | [(unchecked-byte 0x05) (unchecked-byte 0x00)])) 85 | 86 | ;; ASN.1 encoding for BIT STRING 87 | (defn- asn1-bit-str [n] 88 | (asn1-enc 0x03 (concat 89 | ;; unused bits for padding 90 | [(unchecked-byte 0x00)] 91 | n))) 92 | 93 | ;; ASN.1 encoding for OCTET STRING 94 | (defn- asn1-oct-str [n] 95 | (asn1-enc 0x04 n)) 96 | 97 | ;; PKCS-1 OID value for RSA encryption 98 | ;; see https://www.alvestrand.no/objectid/1.2.840.113549.1.1.1.html 99 | (def ^:private pkcs1-oid "1.2.840.113549.1.1.1") 100 | 101 | ;; RSA public key (only modulus (p x q) and public exponent) 102 | ;; https://tools.ietf.org/html/rfc3447#appendix-A.1.1 103 | (defn public-key 104 | "Return a RSA public key representation of a `key`." 105 | [key] 106 | (asn1-seq 107 | (concat 108 | (asn1-seq 109 | (concat 110 | (asn1-obj 111 | (map #(unchecked-byte %) (oid/oid-to-bytes pkcs1-oid))) 112 | (asn1-null))) 113 | (asn1-bit-str 114 | (asn1-seq 115 | (concat 116 | ;; modulus 117 | (asn1-int (:n key)) 118 | ;; public exponent 119 | (asn1-int (:e key)))))))) 120 | 121 | ;; OpenSSH public key (id_rsa.pub) more familiar for ssh users 122 | ;; 123 | ;; compute item length as required from OpenSSH 124 | ;; 4 bytes format 125 | (defn- openssh-length [c] 126 | (loop [c (.toByteArray (biginteger (count c)))] 127 | (if (= 4 (count c)) 128 | c 129 | (recur (concat [(unchecked-byte 0x00)] c))))) 130 | 131 | ;; concat item length with item represented as byte array 132 | (defn- openssh-item [i] 133 | (let [ba 134 | (cond 135 | (string? i) (.getBytes i) 136 | :else (.toByteArray i))] 137 | (concat 138 | (openssh-length ba) 139 | ba))) 140 | 141 | ;; same information of pem in a slightly different format 142 | (defn openssh-public-key 143 | "Return an OpenSSH public key representation of a `key`." 144 | [key] 145 | (byte-array 146 | (concat 147 | ;; string prefix 148 | (openssh-item "ssh-rsa") 149 | ;; public exponent 150 | (openssh-item (:e key)) 151 | ;; modulus 152 | (openssh-item (:n key))))) 153 | 154 | ;; RSA private key 155 | ;; https://tools.ietf.org/html/rfc3447#appendix-A.1.2 156 | (defn private-key 157 | "Return a RSA private key representation of a `key`." 158 | [key] 159 | (asn1-seq 160 | (concat 161 | (asn1-int (biginteger 0)) 162 | (asn1-seq 163 | (concat 164 | (asn1-obj 165 | (map #(unchecked-byte %) (oid/oid-to-bytes pkcs1-oid))) 166 | (asn1-null))) 167 | (asn1-oct-str 168 | (asn1-seq 169 | (concat 170 | ;; version 171 | (asn1-int (biginteger 0)) 172 | ;; modulus 173 | (asn1-int (:n key)) 174 | ;; public exponent 175 | (asn1-int (:e key)) 176 | ;; private exponent 177 | (asn1-int (:d key)) 178 | ;; prime1 179 | (asn1-int (:p key)) 180 | ;; prime2 181 | (asn1-int (:q key)) 182 | ;; exponent1 183 | (asn1-int (.mod (:d key) (.subtract (:p key) (biginteger 1)))) 184 | ;; exponent2 185 | (asn1-int (.mod (:d key) (.subtract (:q key) (biginteger 1)))) 186 | ;; coefficient 187 | (asn1-int (.modInverse (:q key) (:p key))))))))) 188 | 189 | (defn write-private-key! 190 | "Get the RSA private key from `k` and write it to a file named `f`." 191 | [k f] 192 | (utils/write-private-key! (private-key k) f)) 193 | 194 | (defn write-public-key! 195 | "Get the RSA public key from `k` and write it to a file named `f`." 196 | [k f] 197 | (utils/write-public-key! (public-key k) f)) 198 | 199 | (defn write-openssh-public-key! 200 | "Get the OpenSSH public key from `k` and write it to a file named `f`." 201 | [k f] 202 | (utils/write-openssh-public-key! (openssh-public-key k) f)) 203 | -------------------------------------------------------------------------------- /src/clj_ssh_keygen/oid.clj: -------------------------------------------------------------------------------- 1 | ;; Copyright (c) 2020-2024 Saidone 2 | 3 | (ns clj-ssh-keygen.oid 4 | (:gen-class)) 5 | 6 | (require '[clojure.string :as str]) 7 | 8 | (defn- token-to-bytes [token] 9 | (let [bitlist 10 | (partition-all 11 | 7 12 | ;; prepend zeros to match multiple of 7 length 13 | (concat (repeat (- 7 (rem (count (Integer/toString token 2)) 7)) \0) 14 | (Integer/toString token 2)))] 15 | (concat 16 | (map 17 | #(Integer/valueOf (apply str (cons \1 %)) 2) 18 | (butlast bitlist)) 19 | (list (Integer/valueOf (apply str (cons \0 (last bitlist))) 2))))) 20 | 21 | ;; https://stackoverflow.com/questions/3376357/how-to-convert-object-identifiers-to-hex-strings 22 | (defn oid-to-bytes 23 | "Convert an OID string `oid` to a list of bytes." 24 | [oid] 25 | (let [tokens (map #(Integer/parseInt %) (str/split oid #"\."))] 26 | (flatten 27 | (concat 28 | ;; first two tokens encoded separately 29 | (list (+ (* 40 (first tokens)) (second tokens))) 30 | (map 31 | token-to-bytes 32 | (drop 2 tokens)))))) 33 | -------------------------------------------------------------------------------- /src/clj_ssh_keygen/utils.clj: -------------------------------------------------------------------------------- 1 | ;; Copyright (c) 2020-2024 Saidone 2 | 3 | (ns clj-ssh-keygen.utils 4 | (:import [java.util Base64]) 5 | (:gen-class)) 6 | 7 | ;; wrap string to 72 characters 8 | (defn- wrap-72 [s] 9 | (reduce 10 | #(str %1 %2 "\n") 11 | "" 12 | (map 13 | #(apply str %) 14 | (partition-all 72 s)))) 15 | 16 | (defn write-public-key! 17 | "Encode a RSA public key `k` to base64, wrap to 72 characters and write it to a file named `f`." 18 | [k f] 19 | (spit f 20 | (str 21 | "-----BEGIN PUBLIC KEY-----\n" 22 | (wrap-72 23 | (.encodeToString (Base64/getEncoder) k)) 24 | "-----END PUBLIC KEY-----\n"))) 25 | 26 | (defn write-private-key! 27 | "Encode a RSA private key `k` to base64, wrap to 72 characters and write it to a file named `f`." 28 | [k f] 29 | (spit f 30 | (str 31 | "-----BEGIN PRIVATE KEY-----\n" 32 | (wrap-72 33 | (.encodeToString (Base64/getEncoder) k)) 34 | "-----END PRIVATE KEY-----\n"))) 35 | 36 | (defn write-openssh-public-key! 37 | "Encode an OpenSSH public key `k` to base64 and write it to a file named `f`." 38 | [k f] 39 | (spit f 40 | (str 41 | "ssh-rsa " 42 | (.encodeToString (Base64/getEncoder) k)))) -------------------------------------------------------------------------------- /test/clj_ssh_keygen/core_test.clj: -------------------------------------------------------------------------------- 1 | ;; Copyright (c) 2020-2024 Saidone 2 | 3 | (ns clj-ssh-keygen.core-test 4 | (:require [clojure.test :refer [deftest]] 5 | [clj-ssh-keygen.core :as core])) 6 | 7 | ;; Test keys integrity with openssl 8 | ;; 9 | ;; show public key 10 | ;; $ openssl rsa -noout -text -pubin -inform PEM -in pub.pem 11 | ;; 12 | ;; extract public key from private 13 | ;; $ openssl rsa -pubout -in pvt.pem -out pub.pem 14 | ;; 15 | ;; use key to authenticate on a host 16 | ;; id_rsa.pub must be appended to ~/.ssh/authorized_keys for user on destination host 17 | ;; https://man.openbsd.org/ssh#AUTHENTICATION 18 | ;; $ ssh -i pvt.pem user@host 19 | ;; 20 | ;; awesome online tool for debugging ASN.1 https://lapo.it/asn1js/ 21 | 22 | (deftest keygen 23 | (let [key (core/generate-key)] 24 | (core/write-private-key! key "pvt.pem") 25 | (core/write-public-key! key "pub.pem") 26 | (core/write-openssh-public-key! key "id_rsa.pub"))) 27 | --------------------------------------------------------------------------------