Skip to content

Instantly share code, notes, and snippets.

@kordano
Created March 19, 2018 08:10
Show Gist options
  • Save kordano/008df4f240e1cc3438c4db87a252c49e to your computer and use it in GitHub Desktop.
Save kordano/008df4f240e1cc3438c4db87a252c49e to your computer and use it in GitHub Desktop.
Public Private Key Encryption in Clojure
;; based on http://worace.works/2016/06/05/rsa-cryptography-in-clojure
(def cipher-algorithm "RSA/ECB/PKCS1Padding")
(defn key-pair-generator [length]
(doto (java.security.KeyPairGenerator/getInstance "RSA")
(.initialize length)))
(defn generate-keypair [length]
(assert (>= length 512) "RSA Key must be at least 512 bits long.")
(.generateKeyPair (key-pair-generator length)))
(defn decode64 [str]
(.decode (java.util.Base64/getDecoder) str))
(defn encode64 [bytes]
(.encodeToString (java.util.Base64/getEncoder) bytes))
(defn encrypt [message public-key]
(encode64
(let [cipher (doto (javax.crypto.Cipher/getInstance cipher-algorithm)
(.init javax.crypto.Cipher/ENCRYPT_MODE public-key))]
(.doFinal cipher (.getBytes message)))))
(defn decrypt [message private-key]
(let [cipher (doto (javax.crypto.Cipher/getInstance cipher-algorithm)
(.init javax.crypto.Cipher/DECRYPT_MODE private-key))]
(->> message
decode64
(.doFinal cipher)
(map char)
(apply str))))
(def keypair (generate-keypair 512))
(def public-key (.getPublic keypair))
(def private-key (.getPrivate keypair))
(def message "this is a secret")
(def encrypted-message (encrypt message public-key))
(= message (decrypt encrypted-message private-key))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment