How to XOR Bitstrings in Elixir
tl;dr
Use :crypto.exor/2
from crypto module in Erlang standard library.
Chronicle of My Decent into Rabbit Hole
It started with a simple quiz from Cryptography course in Coursera. I was given a plain text (pt
) and a cipher text (ct
) encrypted with one-time pad, so I just had to do an XOR of ct
and pt
to figure out the one-time pad key.
I didn’t know how to do that in Elixir, so I decided to figure it out.
The plain text was encoded in hexadecimal and has to be converted to binary first. I searched and found that Base
module had decode16/2
function.
I tried straight-up XOR.
Well, that didn’t work. I now had to figure out how to XOR each of corresponding bytes in the pair of bitstrings. Enum
is the obvious first choice for iteration, but bitstring is not an Enumerable
so that was out of option. I decided to use generators instead.
No multiple generators for bitstrings, I guess. Even if that worked, it wouldn’t have done what I wanted. Next idea was to turn bitstrings into lists and operate on them. Like this.
It works well and I got the one-time pad key. But at this point, someone in IRC told me to look into :crypto.exor
.
Well, it seems that I didn’t have to go through all of that. At least I got it right and learned much more about binaries in Elixir, though.