~jonn/snippets

snippets/erlang/binary_stream_editor.erl -rw-r--r-- 1.7 KiB
49b5c365Jonn Problem: XOR hack fails to highlight 0 and NaN 21 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
-module(binary_stream_editor).
-compile(export_all).

%% Solving a CTF problem with Erlang!
%%
%% Bit syntax reference: http://erlang.org/doc/programming_examples/bit_syntax.html

drop_first_bit_of_every_byte(<<_B:1, A:7, Rest/bitstring>>, Acc) ->
  drop_first_bit_of_every_byte(Rest, <<Acc/bitstring, A:7>>);
drop_first_bit_of_every_byte(<<>>, Acc) -> Acc.

drop_last_bit_of_every_byte(<<A:7, _B:1, Rest/bitstring>>, Acc) ->
  drop_last_bit_of_every_byte(Rest, <<Acc/bitstring, A:7>>);
drop_last_bit_of_every_byte(<<>>, Acc) -> Acc.

dup_first_bit_of_every_byte(<<B:1, A:7, Rest/bitstring>>, Acc) ->
  dup_first_bit_of_every_byte(Rest, <<Acc/bitstring, B:1, B:1, A:7>>);
dup_first_bit_of_every_byte(<<>>, Acc) -> Acc.

dup_last_bit_of_every_byte(<<A:7, B:1, Rest/bitstring>>, Acc) ->
  dup_last_bit_of_every_byte(Rest, <<Acc/bitstring, A:7, B:1, B:1>>);
dup_last_bit_of_every_byte(<<>>, Acc) -> Acc.

drop_last_38_bits(<<Good:266, _Bad:38>>) -> <<Good:266>>.
drop_first_38_bits(<<_Bad:38, Good:266>>) -> <<Good:266>>.

and0_last_bit_of_every_byte(<<A:7, Rest/bitstring>>, Acc) ->
  and0_last_bit_of_every_byte(Rest, <<Acc/bitstring, 0:1, A:7>>);
and0_last_bit_of_every_byte(<<LessThanSevenBits/bitstring>>, Acc) ->
  <<Acc/bitstring, LessThanSevenBits/bitstring>>;
and0_last_bit_of_every_byte(<<>>, Acc) -> Acc.

pad_with_zeros(<<X/binary>>) -> X;
pad_with_zeros(<<X/bitstring>>) ->
  Padding = 8 - (bit_size(X) rem 8),
  <<X/bitstring, 0:Padding>>.

main() ->
  {ok, In} = file:read_file("priv/01-binary-stream-editor.data"),
  Out = pad_with_zeros(drop_last_bit_of_every_byte(In, <<>>)),
  io:format("~p~nbit_size: ~p~n", [Out, bit_size(Out)]),
  file:write_file("priv/01-binary-stream-editor.data.out", Out).