Skip to content

Instantly share code, notes, and snippets.

# ericnormand/00 XOR Cypher.md

Last active October 6, 2021 17:42
Show Gist options
• Save ericnormand/b21bea7143211980f84a87fc1b5e463a to your computer and use it in GitHub Desktop.
436 PurelyFunctional.tv Newsletter

XOR Cypher

The XOR Cypher is simple: To encrypt, you do a bitwise XOR of the message with a key. To decrypt it, you XOR it again with the same key.

Write a function `encrypt` that does an XOR encryption of a message string given a key string. If the message is longer than the key, repeat the key.

Note, I see this as an exercise in JVM byte manipulation.

Thanks to this site for the problem idea, where it is rated Expert in JavaScript. The problem has been modified.

Please submit your solutions as comments on this gist.

To subscribe: https://purelyfunctional.tv/newsletter/

### mcuervoe commented Jul 31, 2021

```(defn encrypt [key message]
(->>
(map vector (seq message) (cycle key))
(map (fn [[m k]] (bit-xor (int m) (int k))))
(map (fn [i] (format "%02x" i)))
(apply str)))

(defn decrypt [key message]
(let [int-seq (->> message
(partition 2)
(map (fn [[a b]] (str "0x" a b)))
(map read-string))]
(->> (map vector int-seq (cycle key))
(map (fn [[m k]] (bit-xor m (int k))))
(map char)
(apply str))))

(encrypt "abc" "hello world")
=> "09070f0d0d43160d110d06"
(decrypt "abc" (encrypt "abc" "hello world"))
=> "hello world"```

### KingCode commented Oct 6, 2021

```(defn key-bytes [msg key]
(->> key cycle (take (count msg)) (apply str)
(map int)))

(defn encrypt [msg key]
(let [msg-bytes (->> msg (map int))
key-bytes (key-bytes msg key)]
(->>
(map bit-xor msg-bytes key-bytes)
(map char)
(apply str))))

(defn decrypt [encrypted key]
(encrypt encrypted key))```

to join this conversation on GitHub. Already have an account? Sign in to comment