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]) (:import (java.security SecureRandom) (java.util Base64)))
- We attach documentation to our namespace (
(ns name docstring?))
- We opt out of including
clojure.core/bytesin our namespace as we want that name
- We import a secure random number generator and Base64 encoder from Java’s standard library
Time to make use of the coveted
(defn bytes [size] (let [seed (byte-array size)] (.nextBytes (SecureRandom.) seed) seed))
And a corresponding function to give us a base-64-encoded string of random bytes.
(defn base64 [size] (.encodeToString (Base64/getEncoder) (bytes size)))
Time to make use of our code. Let’s have 48 bytes of randomness.