Skip to content

Instantly share code, notes, and snippets.

@whilo
Last active December 27, 2015 17:39
Show Gist options
  • Save whilo/7363179 to your computer and use it in GitHub Desktop.
Save whilo/7363179 to your computer and use it in GitHub Desktop.
RC4 in Clojure
(ns rc4.core)
(defn init-sbox [enc-key]
(let [k (mapv int enc-key)
L (count enc-key)]
(loop [s (into [] (range 0 256)) i 0 j 0]
(if (= i 256) s
(let [j (mod (+ j (s i) (k (mod i L))) 256)]
(recur (assoc s i (s j) j (s i)) (inc i) j))))))
(defn crypt [clear s-box]
(loop [enc (vector (repeat (count clear) 0))
s s-box n 0 i 0 j 0]
(if (= n (count clear)) enc
(let [i (mod (inc i) 256)
j (mod (+ j (s i)) 256)
s (assoc s i (s j) j (s i))
random (s (mod (+ (s i) (s j)) 256))]
(recur (assoc enc n (bit-xor random (int (nth clear n))))
s (inc n) i j)))))
(def cyph (crypt "Hello World!" (init-sbox "abc")))
; checked against http://www.joonis.de/de/code/rc4-algorithm
(apply str (map char (crypt cyph (init-sbox "abc"))))
; => "Hello World!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment