Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Last active October 6, 2021 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericnormand/b21bea7143211980f84a87fc1b5e463a to your computer and use it in GitHub Desktop.
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/

@miner
Copy link

miner commented Jul 27, 2021

(def ^java.nio.charset.Charset utf8 (java.nio.charset.Charset/forName "UTF-8"))

(defn enc8 [key message]
  (let [utf-bytes (fn [^String s] (.getBytes s utf8))]
    (String. (byte-array (map bit-xor (cycle (utf-bytes key)) (utf-bytes message))))))

@mcuervoe
Copy link

(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
Copy link

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))

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