-
Notifications
You must be signed in to change notification settings - Fork 179
/
utils.go
69 lines (58 loc) · 1.47 KB
/
utils.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 ring
type Dimensions struct {
Rows, Cols int
}
// EvalPolyModP evaluates y = sum poly[i] * x^{i} mod p.
func EvalPolyModP(x uint64, poly []uint64, p uint64) (y uint64) {
brc := BRedConstant(p)
y = poly[len(poly)-1]
for i := len(poly) - 2; i >= 0; i-- {
y = BRed(y, x, p, brc)
y = CRed(y+poly[i], p)
}
return
}
// Min returns the minimum between to int
func Min(x, y int) int {
if x > y {
return y
}
return x
}
// ModExp performs the modular exponentiation x^e mod p,
// x and p are required to be at most 64 bits to avoid an overflow.
func ModExp(x, e, p uint64) (result uint64) {
brc := BRedConstant(p)
result = 1
for i := e; i > 0; i >>= 1 {
if i&1 == 1 {
result = BRed(result, x, p, brc)
}
x = BRed(x, x, p, brc)
}
return result
}
// ModExpPow2 performs the modular exponentiation x^e mod p, where p is a power of two,
// x and p are required to be at most 64 bits to avoid an overflow.
func ModExpPow2(x, e, p uint64) (result uint64) {
result = 1
for i := e; i > 0; i >>= 1 {
if i&1 == 1 {
result *= x
}
x *= x
}
return result & (p - 1)
}
// ModexpMontgomery performs the modular exponentiation x^e mod p,
// where x is in Montgomery form, and returns x^e in Montgomery form.
func ModexpMontgomery(x uint64, e int, q, qInv uint64, bredconstant []uint64) (result uint64) {
result = MForm(1, q, bredconstant)
for i := e; i > 0; i >>= 1 {
if i&1 == 1 {
result = MRed(result, x, q, qInv)
}
x = MRed(x, x, q, qInv)
}
return result
}