-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGF2_8.cry
103 lines (75 loc) · 2.02 KB
/
GF2_8.cry
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
type GF2_8 = [8]
type FieldWidth = 8
type FieldSize = 2^^FieldWidth
type Q = FieldSize - 1
irr : [9]
irr = <| x^^8 + x^^4 + x^^3 + x^^2 + 1 |>
nextPow : GF2_8 -> GF2_8
nextPow b =
if b@0 then
reduced
else
b << 1
where reduced = tail ((b # zero) ^ irr)
exptable : [2*FieldSize]GF2_8
exptable = take tab
where tab = [1] # [ nextPow b | b <- tab ]
logtable : [FieldSize][8]
logtable =
[ 0 ] # [ findLog i | i <- [ 1 .. Q ] ]
findLog : [8] -> [8]
findLog i = go 0
where go j = if (exptable@j) == i then j else go (j+1)
// logtable : [FieldSize][8]
// logtable = (tables@(`Q:[8])).2
// where
// tables : [_]([8], GF2_8, [FieldSize][8])
// tables = [ (0, 1, zero:[FieldSize][8]) ]
// #
// [ (i+1, nextPow b, replaceAt t b i)
// | (i,b,t) <- tables
// ]
// replaceAt : {a,b,c} (fin c) => [a]b -> [c] -> b -> [a]b
// replaceAt xs i b =
// [ if i == j then b else x
// | x <- xs
// | j <- [0 ...]
// ]
property logexp_correct (x:[8]) =
x == 0 || exptable@(logtable@x) == x
property logexp_correct2 (x:[8]) =
x == 0 || exptable@((zero # logtable@x) + `Q:[16]) == x
zeroMask : [8] -> [8]
zeroMask x = drop`{8} z
where
y : [16]
y = zero # x
z : [16]
z = (y - 1) >> 8
property zeroMask_correct x =
zeroMask x == (if x == 0 then 0xFF else 0x00)
gf28_mult : GF2_8 -> GF2_8 -> GF2_8
gf28_mult x y = (z && d) ^ d
where a = zero # logtable@x
b = zero # logtable@y
c : [16]
c = a + b
d : [8]
d = exptable@c
z : [8]
z = zeroMask x || zeroMask y
// Precondition: y is not 0
gf28_div : GF2_8 -> GF2_8 -> GF2_8
gf28_div x y = (z && d) ^ d
where a = zero # logtable@x
b = zero # logtable@y
c : [16]
c = a + `Q - b
d : [8]
d = exptable@c
z = zeroMask x
property mult_correct (x:GF2_8) (y:GF2_8) =
gf28_mult x y == pmod (pmult x y) irr
property div_correct (x:GF_8) (y:GF2_8) =
y == 0 || pmod (pmult q y) irr == x
where q = gf28_div x y