Created
August 22, 2013 17:53
-
-
Save ecmendenhall/6310552 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns crypto-challenges.core | |
(:require [clojure.edn :refer [read-string]] | |
[clojure.string :refer [lower-case]])) | |
(def alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ") | |
(def base64-values (str alphabet | |
(lower-case alphabet) | |
"0123456789+/")) | |
(defn parse-hex [string] | |
(read-string (str "0x" string))) | |
(defn split-hex-string [string] | |
(map #(apply str %) | |
(partition-all 2 string))) | |
(defn hex->bytes [string] | |
(map parse-hex (split-hex-string string))) | |
(defn decimal->binary [dec] | |
(loop [quotient (bit-shift-right dec 1) | |
remainder (mod dec 2) | |
bits []] | |
(if (= 0 quotient) | |
(let [unpadded (reverse (conj bits remainder 0))] | |
(concat (repeat (- 8 (count unpadded)) 0) | |
unpadded)) | |
(recur (bit-shift-right quotient 1) | |
(mod quotient 2) | |
(conj bits remainder))))) | |
(defn bytes->bits [bytes] | |
(apply concat (map decimal->binary bytes))) | |
(defn bits->decimal [bits] | |
(read-string (str "2r" (apply str bits)))) | |
(defn bits->base64-index [bits] | |
(map bits->decimal (partition-all 6 bits))) | |
(defn bits->base64 [bits] | |
(apply str (map #(nth base64-values %) (bits->base64-index bits)))) | |
(defn bytes->base64 [bytes] | |
(-> bytes | |
bytes->bits | |
bits->base64)) | |
(defn hex->base64 [hex] | |
(-> hex | |
hex->bytes | |
bytes->bits | |
bits->base64)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment