-
Notifications
You must be signed in to change notification settings - Fork 179
/
scalar.go
75 lines (65 loc) · 2.13 KB
/
scalar.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
70
71
72
73
74
75
package ring
import (
"math/big"
)
// RNSScalar represents a scalar value in the Ring (i.e., a degree-0 polynomial) in RNS form.
type RNSScalar []uint64
// NewRNSScalar creates a new Scalar value.
func (r *Ring) NewRNSScalar() RNSScalar {
return make(RNSScalar, r.level+1)
}
// NewRNSScalarFromUInt64 creates a new Scalar initialized with value v.
func (r *Ring) NewRNSScalarFromUInt64(v uint64) (rns RNSScalar) {
rns = make(RNSScalar, r.level+1)
for i, s := range r.SubRings[:r.level+1] {
rns[i] = v % s.Modulus
}
return rns
}
// NewRNSScalarFromBigint creates a new Scalar initialized with value v.
func (r *Ring) NewRNSScalarFromBigint(v *big.Int) (rns RNSScalar) {
rns = make(RNSScalar, r.level+1)
tmp0 := new(big.Int)
tmp1 := new(big.Int)
for i, s := range r.SubRings[:r.level+1] {
rns[i] = tmp0.Mod(v, tmp1.SetUint64(s.Modulus)).Uint64()
}
return rns
}
// MFormRNSScalar switches an RNS scalar to the Montgomery domain.
// s2 = s1<<64 mod Q
func (r *Ring) MFormRNSScalar(s1, s2 RNSScalar) {
for i, s := range r.SubRings[:r.level+1] {
s2[i] = MForm(s1[i], s.Modulus, s.BRedConstant)
}
}
// NegRNSScalar evaluates s2 = -s1.
func (r *Ring) NegRNSScalar(s1, s2 RNSScalar) {
for i, s := range r.SubRings[:r.level+1] {
s2[i] = s.Modulus - s1[i]
}
}
// SubRNSScalar subtracts s2 to s1 and stores the result in sout.
func (r *Ring) SubRNSScalar(s1, s2, sout RNSScalar) {
for i, s := range r.SubRings[:r.level+1] {
if s2[i] > s1[i] {
sout[i] = s1[i] + s.Modulus - s2[i]
} else {
sout[i] = s1[i] - s2[i]
}
}
}
// MulRNSScalar multiplies s1 and s2 and stores the result in sout.
// Multiplication is operated with Montgomery.
func (r *Ring) MulRNSScalar(s1, s2, sout RNSScalar) {
for i, s := range r.SubRings[:r.level+1] {
sout[i] = MRedLazy(s1[i], s2[i], s.Modulus, s.MRedConstant)
}
}
// Inverse computes the modular inverse of a scalar a expressed in a CRT decomposition.
// The inversion is done in-place and assumes that a is in Montgomery form.
func (r *Ring) Inverse(a RNSScalar) {
for i, s := range r.SubRings[:r.level+1] {
a[i] = ModexpMontgomery(a[i], int(s.Modulus-2), s.Modulus, s.MRedConstant, s.BRedConstant)
}
}