nixfiles/libs/aes/ascii.nix
Sebastian Walz 9f7b02e1cd
Tohu vaBohu
2023-04-03 14:38:02 +02:00

120 lines
3.0 KiB
Nix

let
inherit(builtins) bitAnd concatMap elemAt foldl' genList length map split;
byteAt
= dword:
index:
if index == 0 then bitAnd dword 255
else if index == 1 then bitAnd (dword / shift1) 255
else if index == 2 then bitAnd (dword / shift2) 255
else if index == 3 then dword / shift3
else null;
shift1 = 256;
shift2 = 256 * 256;
shift3 = 256 * 256 * 256;
hexByte
= byte:
let
h = byte / 16;
l = bitAnd byte 15;
x = [ "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "a" "b" "c" "d" "e" "f" ];
x' = elemAt x;
in
"${x' h}${x' l}";
hex
= dword:
let
dword' = byteAt dword;
a = hexByte (dword' 0);
b = hexByte (dword' 1);
c = hexByte (dword' 2);
d = hexByte (dword' 3);
in
"${a}${b}${c}${d}";
toChars
= text:
concatMap
(
x:
if x == ""
then
[]
else
x
)
(split "(.)" text);
ascii
= toChars
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz(|)~";
char2int
= (
foldl'
(
{ result, index }:
character:
{
result
= result
// {
${character} = index;
};
index = index + 1;
}
)
{
index = 32;
result
= {
"\t" = 9;
"\n" = 10;
"\r" = 13;
};
}
ascii
).result;
toIntegers
= text:
map
(
character:
char2int.${character}
)
(toChars text);
toDWords
= data:
let
data'
= if __typeOf data == "string"
then
toIntegers data
else
data;
data'' = data' ++ [ 0 0 0 ];
d = elemAt data'';
in
genList
(
i:
let
i' = i * 4;
in
(d i')
+ (d (i' + 1)) * shift1
+ (d (i' + 2)) * shift2
+ (d (i' + 3)) * shift3
)
((length data'') / 4);
in
{
inherit hex toIntegers toDWords;
}