-
Notifications
You must be signed in to change notification settings - Fork 15
/
byteops.go
82 lines (75 loc) · 2.23 KB
/
byteops.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
76
77
78
79
80
81
82
/* SPDX-FileCopyrightText: © 2020-2024 Nadim Kobeissi <[email protected]>
* SPDX-License-Identifier: MIT */
package kyberk2so
// byteopsLoad32 returns a 32-bit unsigned integer loaded from byte x.
func byteopsLoad32(x []byte) uint32 {
var r uint32
r = uint32(x[0])
r = r | (uint32(x[1]) << 8)
r = r | (uint32(x[2]) << 16)
r = r | (uint32(x[3]) << 24)
return r
}
// byteopsLoad24 returns a 32-bit unsigned integer loaded from byte x.
func byteopsLoad24(x []byte) uint32 {
var r uint32
r = uint32(x[0])
r = r | (uint32(x[1]) << 8)
r = r | (uint32(x[2]) << 16)
return r
}
// byteopsCbd computers a polynomial with coefficients distributed
// according to a centered binomial distribution with parameter eta,
// given an array of uniformly random bytes.
func byteopsCbd(buf []byte, paramsK int) poly {
var t, d uint32
var a, b int16
var r poly
switch paramsK {
case 2:
for i := 0; i < paramsN/4; i++ {
t = byteopsLoad24(buf[3*i:])
d = t & 0x00249249
d = d + ((t >> 1) & 0x00249249)
d = d + ((t >> 2) & 0x00249249)
for j := 0; j < 4; j++ {
a = int16((d >> (6*j + 0)) & 0x7)
b = int16((d >> (6*j + paramsETAK512)) & 0x7)
r[4*i+j] = a - b
}
}
default:
for i := 0; i < paramsN/8; i++ {
t = byteopsLoad32(buf[4*i:])
d = t & 0x55555555
d = d + ((t >> 1) & 0x55555555)
for j := 0; j < 8; j++ {
a = int16((d >> (4*j + 0)) & 0x3)
b = int16((d >> (4*j + paramsETAK768K1024)) & 0x3)
r[8*i+j] = a - b
}
}
}
return r
}
// byteopsMontgomeryReduce computes a Montgomery reduction; given
// a 32-bit integer `a`, returns `a * R^-1 mod Q` where `R=2^16`.
func byteopsMontgomeryReduce(a int32) int16 {
return int16((a - int32(int16(a*int32(paramsQInv)))*int32(paramsQ)) >> 16)
}
// byteopsBarrettReduce computes a Barrett reduction; given
// a 16-bit integer `a`, returns a 16-bit integer congruent to
// `a mod Q` in {0,...,Q}.
func byteopsBarrettReduce(a int16) int16 {
var t int16
var v int16 = int16(((uint32(1) << 26) + uint32(paramsQ/2)) / uint32(paramsQ))
t = int16(int32(v) * int32(a) >> 26)
t = t * int16(paramsQ)
return a - t
}
// byteopsCSubQ conditionally subtracts Q from a.
func byteopsCSubQ(a int16) int16 {
a = a - int16(paramsQ)
a = a + ((a >> 15) & int16(paramsQ))
return a
}