Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Last active December 17, 2015 04:49
Show Gist options
  • Save martintrojer/5553101 to your computer and use it in GitHub Desktop.
Save martintrojer/5553101 to your computer and use it in GitHub Desktop.
Base64 UUID
;; [commons-codec "1.7"]
(ns b64uuid
(:import [java.util UUID]
[java.nio ByteBuffer]
[org.apache.commons.codec.binary Base64]))
(defn uuid->b64 [^UUID uuid]
(let [ba (-> (ByteBuffer/wrap (make-array Byte/TYPE 16))
(.putLong (.getMostSignificantBits uuid))
(.putLong (.getLeastSignificantBits uuid))
(.array))]
(String. (Base64/encodeBase64URLSafeString ba))))
(defn b64->uuid [^String b64uuid]
(let [bb (ByteBuffer/wrap (Base64/decodeBase64 b64uuid))]
(UUID. (.getLong bb) (.getLong bb))))
;; -----
(let [u (UUID/randomUUID)
b64u (uuid->b64 u)]
(= u (b64->uuid b64u)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment