]> gitweb.factorcode.org Git - factor.git/blob - extra/crypto/common/common.factor
651bd51774164a7316a16239119557c7fcc7176a
[factor.git] / extra / crypto / common / common.factor
1 USING: arrays kernel io io.binary sbufs splitting grouping
2 strings sequences namespaces math math.parser parser
3 hints math.bitfields.lib assocs ;
4 IN: crypto.common
5
6 : w+ ( int int -- int ) + 32 bits ; inline
7
8 : (nth-int) ( string n -- int )
9     2 shift dup 4 + rot <slice> ; inline
10     
11 : nth-int ( string n -- int ) (nth-int) le> ; inline
12     
13 : nth-int-be ( string n -- int ) (nth-int) be> ; inline
14
15 : update ( num var -- ) [ w+ ] change ; inline
16     
17 : calculate-pad-length ( length -- pad-length )
18     dup 56 < 55 119 ? swap - ;
19
20 : preprocess-plaintext ( string big-endian? -- padded-string )
21     #! pad 0x80 then 00 til 8 bytes left, then 64bit length in bits
22     >r >sbuf r> over [
23         HEX: 80 ,
24         dup length HEX: 3f bitand
25         calculate-pad-length 0 <string> %
26         length 3 shift 8 rot [ >be ] [ >le ] if %
27     ] "" make over push-all ;
28
29 SYMBOL: bytes-read
30 SYMBOL: big-endian?
31
32 : pad-last-block ( str big-endian? length -- str )
33     [
34         rot %
35         HEX: 80 ,
36         dup HEX: 3f bitand calculate-pad-length 0 <string> %
37         3 shift 8 rot [ >be ] [ >le ] if %
38     ] "" make 64 group ;
39
40 : update-old-new ( old new -- )
41     [ get >r get r> ] 2keep >r >r w+ dup r> set r> set ; inline
42
43 : slice3 ( n seq -- a b c ) >r dup 3 + r> <slice> first3 ;
44
45 : seq>2seq ( seq -- seq1 seq2 )
46     #! { abcdefgh } -> { aceg } { bdfh }
47     2 group flip dup empty? [ drop { } { } ] [ first2 ] if ;
48
49 : 2seq>seq ( seq1 seq2 -- seq )
50     #! { aceg } { bdfh } -> { abcdefgh }
51     [ zip concat ] keep like ;
52
53 : mod-nth ( n seq -- elt )
54     #! 5 "abcd" -> b
55     [ length mod ] [ nth ] bi ;