-
Notifications
You must be signed in to change notification settings - Fork 0
/
polynomial.go
69 lines (59 loc) · 1.25 KB
/
polynomial.go
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
package shamir
import (
"crypto/rand"
"io"
)
// evaluate the polynomial at the given point
func eval(p []byte, x byte) (result byte) {
if x == 0 {
return p[0]
}
// Horner's scheme
for i := 1; i <= len(p); i++ {
result = mul(result, x) ^ p[len(p)-i]
}
return
}
// generates a random n-degree polynomial w/ a given x-intercept
func generate(degree byte, x byte) ([]byte, error) {
result := make([]byte, degree+1)
result[0] = x
buf := make([]byte, degree-1)
if _, err := io.ReadFull(rand.Reader, buf); err != nil {
return nil, err
}
for i := byte(1); i < degree; i++ {
result[i] = buf[i-1]
}
// the Nth term can't be zero, or else it's a (N-1) degree polynomial
for {
buf = make([]byte, 1)
if _, err := io.ReadFull(rand.Reader, buf); err != nil {
return nil, err
}
if buf[0] != 0 {
result[degree] = buf[0]
return result, nil
}
}
}
// an input/output pair
type pair struct {
x, y byte
}
// Lagrange interpolation
func interpolate(points []pair, x byte) (value byte) {
for i, a := range points {
weight := byte(1)
for j, b := range points {
if i != j {
top := x ^ b.x
bottom := a.x ^ b.x
factor := div(top, bottom)
weight = mul(weight, factor)
}
}
value = value ^ mul(weight, a.y)
}
return
}