Show me the code

Let’s jump straight into some code to get the grey matter tingling. We’ll move ourselves into a namespace and leverage a few of the features on offer.

(ns app
  "Documentation can capture the why; handy if the question ever comes up."
  (:refer-clojure :exclude [bytes])
   ( SecureRandom)
   (java.util Base64)))
  1. We attach documentation to our namespace ((ns name docstring?))
  2. We opt out of including clojure.core/bytes in our namespace as we want that name
  3. We import a secure random number generator and Base64 encoder from Java’s standard library

Time to make use of the coveted bytes name:

(defn bytes
  (let [seed (byte-array size)]
    (.nextBytes (SecureRandom.) seed)

And a corresponding function to give us a base-64-encoded string of random bytes.

(defn base64
  (.encodeToString (Base64/getEncoder) (bytes size)))

Time to make use of our code. Let’s have 48 bytes of randomness.