]> gitweb.factorcode.org Git - factor.git/blob - extra/crypto/aes/utils/utils.factor
4336bcc92f7ede08e750fb3a586e2ebe52ef908f
[factor.git] / extra / crypto / aes / utils / utils.factor
1 ! Copyright (C) 2013 Fred Alger
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays columns combinators generalizations grouping
4 kernel locals math math.bitwise prettyprint sequences
5 sequences.private ;
6 IN: crypto.aes.utils
7 : gb0 ( a -- a0 ) 0xff bitand ; inline
8 : gb1 ( a -- a1 ) -8 shift gb0 ; inline
9 : gb2 ( a -- a2 ) -16 shift gb0 ; inline
10 : gb3 ( a -- a3 ) -24 shift gb0 ; inline
11
12 #! pack 4 bytes into 32-bit unsigned int
13 #!  a3 is msb
14 : >ui32 ( a0 a1 a2 a3 -- a )
15     [ 8 shift ] [ 16 shift ] [ 24 shift ] tri*
16     bitor bitor bitor 32 bits ;
17
18 #! inverse of ui32
19 : ui32> ( word -- a0 a1 a2 a3 )
20     [ gb0 ] keep [ gb1 ] keep [ gb2 ] keep gb3 ; inline
21
22 : ui32-rev> ( word -- a3 a2 a1 a0 )
23     [ gb3 ] keep [ gb2 ] keep [ gb1 ] keep gb0 ; inline
24
25 : bytes>words ( seq -- seq )
26     4 <groups> [ <reversed> first4 >ui32 ] V{ } map-as ;
27
28 : .t ( seq -- )
29     reverse
30     {
31         [ [ gb0 ] map first4 >ui32 ]
32         [ [ gb1 ] map first4 >ui32 ]
33         [ [ gb2 ] map first4 >ui32 ]
34         [ [ gb3 ] map first4 >ui32 ]
35     } cleave .h .h .h .h ;
36
37
38 #! given 4 columns, output the first diagonal, i.e.
39 #!  C[0,0] C[1,1] C[2,2] C[3,3]
40 : first-diag ( c0 c1 c2 c3 -- a0 a1 a2 a3 )
41     { [ gb3 ] [ gb2 ] [ gb1 ] [ gb0 ] } spread ;
42
43 : (4rot) ( c0 c1 c2 c3 -- c1 c2 c3 c0 ) 4 nrot ; inline
44 : second-diag ( c0 c1 c2 c3 -- a0 a1 a2 a3 ) (4rot) first-diag ;
45 : third-diag  ( c0 c1 c2 c3 -- a0 a1 a2 a3 ) (4rot) second-diag ;
46 : fourth-diag ( c0 c1 c2 c3 -- a0 a1 a2 a3 ) (4rot) third-diag ;
47
48 #! given 4 columns, output the first reverse diagonal, i.e.
49 #!  C[0,0] C[3,1] C[2,2] C[1,3]
50 :: (-rev) ( c0 c1 c2 c3 -- c0 c3 c2 c1 ) c0 c3 c2 c1 ; inline
51 : -first-diag  ( c0 c1 c2 c3 -- a0 a1 a2 a3 ) (-rev) first-diag ;
52 : -second-diag ( c0 c1 c2 c3 -- a0 a1 a2 a3 ) (-rev) (4rot) first-diag ;
53 : -third-diag  ( c0 c1 c2 c3 -- a0 a1 a2 a3 ) (-rev) (4rot) second-diag ;
54 : -fourth-diag ( c0 c1 c2 c3 -- a0 a1 a2 a3 ) (-rev) (4rot) third-diag ;
55
56 :: set-first4-unsafe ( seq a0 a1 a2 a3 -- )
57     a0 0 seq set-nth-unsafe
58     a1 1 seq set-nth-unsafe
59     a2 2 seq set-nth-unsafe
60     a3 3 seq set-nth-unsafe ;
61
62 : 4th-from-end ( seq -- el )
63     [ length 4 - ] keep nth ;
64