Add a password generator
[sandbox] / cryptopals / 01.03 / hex.erl
1 -module(hex).
2 -export([decode/1,encode/1,fixed_xor/2,single_byte_xor/2]).
3
4 data_in_pairs([]) -> [];
5 data_in_pairs([C1,C2|Tail]) -> [ [C1] ++ [C2] | data_in_pairs(Tail) ].
6  
7 int_to_hex(N) when N < 256 -> [hex(N div 16), hex(N rem 16)].
8  
9 hex(N) when (0  =< N) and (N < 10) -> $0 + N;
10 hex(N) when (10 =< N) and (N < 16) -> $a + (N-10).
11
12 decode(Data) -> [ list_to_integer(P,16) || P <- data_in_pairs(Data) ]. 
13 encode(L) -> string:join(lists:map(fun(X) -> int_to_hex(X) end, L), "").
14
15 fixed_xor(Data1,Data2) ->
16     lists:zipwith(
17         fun(P1,P2) -> P1 bxor P2 end,
18         Data1,
19         Data2).
20
21 single_byte_xor(Byte, Data) ->
22     fixed_xor(lists:duplicate(length(Data),Byte),Data).