Guest User

Untitled

a guest
Nov 21st, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. (ns lazy.utils.signing
  2. (import
  3. (java.io StringReader)
  4. (java.security Security Signature)
  5. (org.apache.commons.codec.binary Base64)
  6. (org.bouncycastle.jce.provider BouncyCastleProvider)
  7. (org.bouncycastle.openssl PEMReader))
  8. (:use [cheshire.core :as json])
  9. (:require [clojure.string :as string]))
  10.  
  11. ;; hook up the BouncyCastleProvider which makes PEM things easier for us
  12. (Security/addProvider (BouncyCastleProvider.))
  13.  
  14. (defn get-keypair
  15. "Get a KeyPair from a PEM in a string"
  16. [pem]
  17. (let [sr (StringReader. pem) ;; have to create a StringReader
  18. pemreader (PEMReader. sr)] ;; and then create a PEMReader
  19. (.readObject pemreader))) ;; and then read that. point. java
  20.  
  21. (defn get-keypair-filename
  22. "Return a keypair from the file named `fn`"
  23. [filename]
  24. (get-keypair (slurp filename)))
  25.  
  26. (defn sign
  27. "Sign bytes `b` given a KeyPair `keypair` and a String"
  28. [keypair b]
  29. (let [sig (doto
  30. (Signature/getInstance "SHA1withRSA")
  31. (.initSign (.getPrivate keypair)) ;; initSign w/ the private key from the keypair
  32. (.update b))] ;; and add the bytes to it
  33. (.sign sig)))
  34.  
  35. (defn verify
  36. "Verify that a base64 encoded byte array (v) is a valid signed string"
  37. [keypair b v]
  38. (let [sig (doto
  39. (Signature/getInstance "SHA1withRSA")
  40. (.initVerify (.getPublic keypair)) ;; initSign w/ the private key from the keypair
  41. (.update b))] ;; and add the bytes to it
  42. (.verify sig v))) ;; now verify the bytes passed in `v`
  43.  
  44. (def ^:dynamic keypair)
  45.  
  46. (defmacro with-keypair
  47. "Run functions that expect a pre-defined keypair"
  48. [kp & body]
  49. `(binding [keypair ~kp]
  50. (do ~@body)))
  51.  
  52. (defn sign-obj
  53. "Signs a map as a url safe base64 encoded string"
  54. [ob]
  55. (Base64/encodeBase64URLSafeString (sign keypair (json/generate-smile ob))))
  56.  
  57. (defn dumps
  58. "Dump an object into a signed string. Serializes the object into the
  59. string so it can later be retrieved."
  60. [ob]
  61. (string/join ":"
  62. [(Base64/encodeBase64URLSafeString (json/generate-smile ob))
  63. (sign-obj ob)]))
  64.  
  65. (defn loads
  66. "Load an object from a signed string and verify it.
  67. Returns nil if not valid, otherwise returns the deserialized object."
  68. [s]
  69. (let [val (string/split s #":" 2)
  70. b (Base64/decodeBase64 (nth val 0))]
  71. (cond
  72. (verify keypair b (Base64/decodeBase64 (nth val 1))) (json/decode-smile b)
  73. :else nil)))
Add Comment
Please, Sign In to add comment