Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/hrss/hrss.c

raw
1 // Copyright (c) 2018, Google Inc.
2 // SPDX-License-Identifier: ISC
3
4 #include <openssl/hrss.h>
5
6 #include <assert.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9
10 #include <openssl/bn.h>
11 #include <openssl/hmac.h>
12 #include <openssl/mem.h>
13 #include <openssl/rand.h>
14 #include <openssl/sha.h>
15
16 #if defined(_MSC_VER)
17 #define RESTRICT
18 #else
19 #define RESTRICT restrict
20 #endif
21
22 #include "../internal.h"
23 #include "internal.h"
24
25 #if defined(OPENSSL_SSE2)
26 #include <emmintrin.h>
27 #endif
28
29 #if (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && defined(__ARM_NEON)
30 #include <arm_neon.h>
31 #endif
32
33 // This is an implementation of [HRSS], but with a KEM transformation based on
34 // [SXY]. The primary references are:
35
36 // HRSS: https://eprint.iacr.org/2017/667.pdf
37 // HRSSNIST:
38 // https://csrc.nist.gov/CSRC/media/Projects/Post-Quantum-Cryptography/documents/round-1/submissions/NTRU_HRSS_KEM.zip
39 // SXY: https://eprint.iacr.org/2017/1005.pdf
40 // NTRUTN14:
41 // https://assets.onboardsecurity.com/static/downloads/NTRU/resources/NTRUTech014.pdf
42 // NTRUCOMP: https://eprint.iacr.org/2018/1174
43 // SAFEGCD: https://gcd.cr.yp.to/papers.html#safegcd
44
45
46 // Vector operations.
47 //
48 // A couple of functions in this file can use vector operations to meaningful
49 // effect. If we're building for a target that has a supported vector unit,
50 // |HRSS_HAVE_VECTOR_UNIT| will be defined and |vec_t| will be typedefed to a
51 // 128-bit vector. The following functions abstract over the differences between
52 // NEON and SSE2 for implementing some vector operations.
53
54 // TODO: MSVC can likely also be made to work with vector operations, but ^ must
55 // be replaced with _mm_xor_si128, etc.
56 #if defined(OPENSSL_SSE2) && (defined(__clang__) || !defined(_MSC_VER))
57
58 #define HRSS_HAVE_VECTOR_UNIT
59 typedef __m128i vec_t;
60
61 // vec_capable returns one iff the current platform supports SSE2.
62 static int vec_capable(void) { return 1; }
63
64 // vec_add performs a pair-wise addition of four uint16s from |a| and |b|.
65 static inline vec_t vec_add(vec_t a, vec_t b) { return _mm_add_epi16(a, b); }
66
67 // vec_sub performs a pair-wise subtraction of four uint16s from |a| and |b|.
68 static inline vec_t vec_sub(vec_t a, vec_t b) { return _mm_sub_epi16(a, b); }
69
70 // vec_mul multiplies each uint16_t in |a| by |b| and returns the resulting
71 // vector.
72 static inline vec_t vec_mul(vec_t a, uint16_t b) {
73 return _mm_mullo_epi16(a, _mm_set1_epi16(b));
74 }
75
76 // vec_fma multiplies each uint16_t in |b| by |c|, adds the result to |a|, and
77 // returns the resulting vector.
78 static inline vec_t vec_fma(vec_t a, vec_t b, uint16_t c) {
79 return _mm_add_epi16(a, _mm_mullo_epi16(b, _mm_set1_epi16(c)));
80 }
81
82 // vec3_rshift_word right-shifts the 24 uint16_t's in |v| by one uint16.
83 static inline void vec3_rshift_word(vec_t v[3]) {
84 // Intel's left and right shifting is backwards compared to the order in
85 // memory because they're based on little-endian order of words (and not just
86 // bytes). So the shifts in this function will be backwards from what one
87 // might expect.
88 const __m128i carry0 = _mm_srli_si128(v[0], 14);
89 v[0] = _mm_slli_si128(v[0], 2);
90
91 const __m128i carry1 = _mm_srli_si128(v[1], 14);
92 v[1] = _mm_slli_si128(v[1], 2);
93 v[1] |= carry0;
94
95 v[2] = _mm_slli_si128(v[2], 2);
96 v[2] |= carry1;
97 }
98
99 // vec4_rshift_word right-shifts the 32 uint16_t's in |v| by one uint16.
100 static inline void vec4_rshift_word(vec_t v[4]) {
101 // Intel's left and right shifting is backwards compared to the order in
102 // memory because they're based on little-endian order of words (and not just
103 // bytes). So the shifts in this function will be backwards from what one
104 // might expect.
105 const __m128i carry0 = _mm_srli_si128(v[0], 14);
106 v[0] = _mm_slli_si128(v[0], 2);
107
108 const __m128i carry1 = _mm_srli_si128(v[1], 14);
109 v[1] = _mm_slli_si128(v[1], 2);
110 v[1] |= carry0;
111
112 const __m128i carry2 = _mm_srli_si128(v[2], 14);
113 v[2] = _mm_slli_si128(v[2], 2);
114 v[2] |= carry1;
115
116 v[3] = _mm_slli_si128(v[3], 2);
117 v[3] |= carry2;
118 }
119
120 // vec_merge_3_5 takes the final three uint16_t's from |left|, appends the first
121 // five from |right|, and returns the resulting vector.
122 static inline vec_t vec_merge_3_5(vec_t left, vec_t right) {
123 return _mm_srli_si128(left, 10) | _mm_slli_si128(right, 6);
124 }
125
126 // poly3_vec_lshift1 left-shifts the 768 bits in |a_s|, and in |a_a|, by one
127 // bit.
128 static inline void poly3_vec_lshift1(vec_t a_s[6], vec_t a_a[6]) {
129 vec_t carry_s = {0};
130 vec_t carry_a = {0};
131
132 for (int i = 0; i < 6; i++) {
133 vec_t next_carry_s = _mm_srli_epi64(a_s[i], 63);
134 a_s[i] = _mm_slli_epi64(a_s[i], 1);
135 a_s[i] |= _mm_slli_si128(next_carry_s, 8);
136 a_s[i] |= carry_s;
137 carry_s = _mm_srli_si128(next_carry_s, 8);
138
139 vec_t next_carry_a = _mm_srli_epi64(a_a[i], 63);
140 a_a[i] = _mm_slli_epi64(a_a[i], 1);
141 a_a[i] |= _mm_slli_si128(next_carry_a, 8);
142 a_a[i] |= carry_a;
143 carry_a = _mm_srli_si128(next_carry_a, 8);
144 }
145 }
146
147 // poly3_vec_rshift1 right-shifts the 768 bits in |a_s|, and in |a_a|, by one
148 // bit.
149 static inline void poly3_vec_rshift1(vec_t a_s[6], vec_t a_a[6]) {
150 vec_t carry_s = {0};
151 vec_t carry_a = {0};
152
153 for (int i = 5; i >= 0; i--) {
154 const vec_t next_carry_s = _mm_slli_epi64(a_s[i], 63);
155 a_s[i] = _mm_srli_epi64(a_s[i], 1);
156 a_s[i] |= _mm_srli_si128(next_carry_s, 8);
157 a_s[i] |= carry_s;
158 carry_s = _mm_slli_si128(next_carry_s, 8);
159
160 const vec_t next_carry_a = _mm_slli_epi64(a_a[i], 63);
161 a_a[i] = _mm_srli_epi64(a_a[i], 1);
162 a_a[i] |= _mm_srli_si128(next_carry_a, 8);
163 a_a[i] |= carry_a;
164 carry_a = _mm_slli_si128(next_carry_a, 8);
165 }
166 }
167
168 // vec_broadcast_bit duplicates the least-significant bit in |a| to all bits in
169 // a vector and returns the result.
170 static inline vec_t vec_broadcast_bit(vec_t a) {
171 return _mm_shuffle_epi32(_mm_srai_epi32(_mm_slli_epi64(a, 63), 31), 0x55);
172 }
173
174 // vec_get_word returns the |i|th uint16_t in |v|. (This is a macro because the
175 // compiler requires that |i| be a compile-time constant.)
176 #define vec_get_word(v, i) _mm_extract_epi16(v, i)
177
178 #elif (defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64)) && defined(__ARM_NEON)
179
180 #define HRSS_HAVE_VECTOR_UNIT
181 // The Intel vector type |__m128i| is automatically aligned to a 16-byte
182 // boundary. But, I can't find any information about |uint16x8_t| should
183 // necessarily be aligned to a 16-byte boundary. We verify 16-byte alignment in
184 // |poly_mul_vec()|, so try to force alignment here.
185 typedef uint16x8_t vec_t __attribute__ ((aligned (16)));
186
187 // These functions perform the same actions as the SSE2 function of the same
188 // name, above.
189
190 static int vec_capable(void) { return CRYPTO_is_NEON_capable(); }
191
192 static inline vec_t vec_add(vec_t a, vec_t b) { return a + b; }
193
194 static inline vec_t vec_sub(vec_t a, vec_t b) { return a - b; }
195
196 static inline vec_t vec_mul(vec_t a, uint16_t b) { return vmulq_n_u16(a, b); }
197
198 static inline vec_t vec_fma(vec_t a, vec_t b, uint16_t c) {
199 return vmlaq_n_u16(a, b, c);
200 }
201
202 static inline void vec3_rshift_word(vec_t v[3]) {
203 const uint16x8_t kZero = {0};
204 v[2] = vextq_u16(v[1], v[2], 7);
205 v[1] = vextq_u16(v[0], v[1], 7);
206 v[0] = vextq_u16(kZero, v[0], 7);
207 }
208
209 static inline void vec4_rshift_word(vec_t v[4]) {
210 const uint16x8_t kZero = {0};
211 v[3] = vextq_u16(v[2], v[3], 7);
212 v[2] = vextq_u16(v[1], v[2], 7);
213 v[1] = vextq_u16(v[0], v[1], 7);
214 v[0] = vextq_u16(kZero, v[0], 7);
215 }
216
217 static inline vec_t vec_merge_3_5(vec_t left, vec_t right) {
218 return vextq_u16(left, right, 5);
219 }
220
221 static inline uint16_t vec_get_word(vec_t v, unsigned i) {
222 return v[i];
223 }
224
225 #if !defined(OPENSSL_AARCH64)
226
227 static inline vec_t vec_broadcast_bit(vec_t a) {
228 a = (vec_t)vshrq_n_s16(((int16x8_t)a) << 15, 15);
229 return vdupq_lane_u16(vget_low_u16(a), 0);
230 }
231
232 static inline void poly3_vec_lshift1(vec_t a_s[6], vec_t a_a[6]) {
233 vec_t carry_s = {0};
234 vec_t carry_a = {0};
235 const vec_t kZero = {0};
236
237 for (int i = 0; i < 6; i++) {
238 vec_t next_carry_s = a_s[i] >> 15;
239 a_s[i] <<= 1;
240 a_s[i] |= vextq_u16(kZero, next_carry_s, 7);
241 a_s[i] |= carry_s;
242 carry_s = vextq_u16(next_carry_s, kZero, 7);
243
244 vec_t next_carry_a = a_a[i] >> 15;
245 a_a[i] <<= 1;
246 a_a[i] |= vextq_u16(kZero, next_carry_a, 7);
247 a_a[i] |= carry_a;
248 carry_a = vextq_u16(next_carry_a, kZero, 7);
249 }
250 }
251
252 static inline void poly3_vec_rshift1(vec_t a_s[6], vec_t a_a[6]) {
253 vec_t carry_s = {0};
254 vec_t carry_a = {0};
255 const vec_t kZero = {0};
256
257 for (int i = 5; i >= 0; i--) {
258 vec_t next_carry_s = a_s[i] << 15;
259 a_s[i] >>= 1;
260 a_s[i] |= vextq_u16(next_carry_s, kZero, 1);
261 a_s[i] |= carry_s;
262 carry_s = vextq_u16(kZero, next_carry_s, 1);
263
264 vec_t next_carry_a = a_a[i] << 15;
265 a_a[i] >>= 1;
266 a_a[i] |= vextq_u16(next_carry_a, kZero, 1);
267 a_a[i] |= carry_a;
268 carry_a = vextq_u16(kZero, next_carry_a, 1);
269 }
270 }
271
272 #endif // !OPENSSL_AARCH64
273
274 #endif // (ARM || AARCH64) && NEON
275
276 // Polynomials in this scheme have N terms.
277 // #define N 701
278
279 // Underlying data types and arithmetic operations.
280 // ------------------------------------------------
281
282 // Binary polynomials.
283
284 // poly2 represents a degree-N polynomial over GF(2). The words are in little-
285 // endian order, i.e. the coefficient of x^0 is the LSB of the first word. The
286 // final word is only partially used since N is not a multiple of the word size.
287
288 // Defined in internal.h:
289 // struct poly2 {
290 // crypto_word_t v[WORDS_PER_POLY];
291 // };
292
293 OPENSSL_UNUSED static void hexdump(const void *void_in, size_t len) {
294 const uint8_t *in = (const uint8_t *)void_in;
295 for (size_t i = 0; i < len; i++) {
296 printf("%02x", in[i]);
297 }
298 printf("\n");
299 }
300
301 static void poly2_zero(struct poly2 *p) {
302 OPENSSL_memset(&p->v[0], 0, sizeof(crypto_word_t) * WORDS_PER_POLY);
303 }
304
305 // word_reverse returns |in| with the bits in reverse order.
306 static crypto_word_t word_reverse(crypto_word_t in) {
307 #if defined(OPENSSL_64_BIT)
308 static const crypto_word_t kMasks[6] = {
309 UINT64_C(0x5555555555555555),
310 UINT64_C(0x3333333333333333),
311 UINT64_C(0x0f0f0f0f0f0f0f0f),
312 UINT64_C(0x00ff00ff00ff00ff),
313 UINT64_C(0x0000ffff0000ffff),
314 UINT64_C(0x00000000ffffffff),
315 };
316 #else
317 static const crypto_word_t kMasks[5] = {
318 0x55555555,
319 0x33333333,
320 0x0f0f0f0f,
321 0x00ff00ff,
322 0x0000ffff,
323 };
324 #endif
325
326 for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(kMasks); i++) {
327 in = ((in >> (1 << i)) & kMasks[i]) | ((in & kMasks[i]) << (1 << i));
328 }
329
330 return in;
331 }
332
333 // lsb_to_all replicates the least-significant bit of |v| to all bits of the
334 // word. This is used in bit-slicing operations to make a vector from a fixed
335 // value.
336 static crypto_word_t lsb_to_all(crypto_word_t v) { return 0u - (v & 1); }
337
338 // poly2_mod_phiN reduces |p| by Φ(N).
339 static void poly2_mod_phiN(struct poly2 *p) {
340 // m is the term at x^700, replicated to every bit.
341 const crypto_word_t m =
342 lsb_to_all(p->v[WORDS_PER_POLY - 1] >> (BITS_IN_LAST_WORD - 1));
343 for (size_t i = 0; i < WORDS_PER_POLY; i++) {
344 p->v[i] ^= m;
345 }
346 p->v[WORDS_PER_POLY - 1] &= (UINT64_C(1) << (BITS_IN_LAST_WORD - 1)) - 1;
347 }
348
349 // poly2_reverse_700 reverses the order of the first 700 bits of |in| and writes
350 // the result to |out|.
351 static void poly2_reverse_700(struct poly2 *out, const struct poly2 *in) {
352 struct poly2 t;
353 for (size_t i = 0; i < WORDS_PER_POLY; i++) {
354 t.v[i] = word_reverse(in->v[i]);
355 }
356
357 static const size_t shift = BITS_PER_WORD - ((N-1) % BITS_PER_WORD);
358 for (size_t i = 0; i < WORDS_PER_POLY-1; i++) {
359 out->v[i] = t.v[WORDS_PER_POLY-1-i] >> shift;
360 out->v[i] |= t.v[WORDS_PER_POLY-2-i] << (BITS_PER_WORD - shift);
361 }
362 out->v[WORDS_PER_POLY-1] = t.v[0] >> shift;
363 }
364
365 // poly2_cswap exchanges the values of |a| and |b| if |swap| is all ones.
366 static void poly2_cswap(struct poly2 *a, struct poly2 *b, crypto_word_t swap) {
367 for (size_t i = 0; i < WORDS_PER_POLY; i++) {
368 const crypto_word_t sum = swap & (a->v[i] ^ b->v[i]);
369 a->v[i] ^= sum;
370 b->v[i] ^= sum;
371 }
372 }
373
374 // poly2_fmadd sets |out| to |out| + |in| * m, where m is either
375 // |CONSTTIME_TRUE_W| or |CONSTTIME_FALSE_W|.
376 static void poly2_fmadd(struct poly2 *out, const struct poly2 *in,
377 crypto_word_t m) {
378 for (size_t i = 0; i < WORDS_PER_POLY; i++) {
379 out->v[i] ^= in->v[i] & m;
380 }
381 }
382
383 // poly2_lshift1 left-shifts |p| by one bit.
384 static void poly2_lshift1(struct poly2 *p) {
385 crypto_word_t carry = 0;
386 for (size_t i = 0; i < WORDS_PER_POLY; i++) {
387 const crypto_word_t next_carry = p->v[i] >> (BITS_PER_WORD - 1);
388 p->v[i] <<= 1;
389 p->v[i] |= carry;
390 carry = next_carry;
391 }
392 }
393
394 // poly2_rshift1 right-shifts |p| by one bit.
395 static void poly2_rshift1(struct poly2 *p) {
396 crypto_word_t carry = 0;
397 for (size_t i = WORDS_PER_POLY - 1; i < WORDS_PER_POLY; i--) {
398 const crypto_word_t next_carry = p->v[i] & 1;
399 p->v[i] >>= 1;
400 p->v[i] |= carry << (BITS_PER_WORD - 1);
401 carry = next_carry;
402 }
403 }
404
405 // poly2_clear_top_bits clears the bits in the final word that are only for
406 // alignment.
407 static void poly2_clear_top_bits(struct poly2 *p) {
408 p->v[WORDS_PER_POLY - 1] &= (UINT64_C(1) << BITS_IN_LAST_WORD) - 1;
409 }
410
411 // poly2_top_bits_are_clear returns one iff the extra bits in the final words of
412 // |p| are zero.
413 static int poly2_top_bits_are_clear(const struct poly2 *p) {
414 return (p->v[WORDS_PER_POLY - 1] &
415 ~((UINT64_C(1) << BITS_IN_LAST_WORD) - 1)) == 0;
416 }
417
418 // Ternary polynomials.
419
420 // poly3 represents a degree-N polynomial over GF(3). Each coefficient is
421 // bitsliced across the |s| and |a| arrays, like this:
422 //
423 // s | a | value
424 // -----------------
425 // 0 | 0 | 0
426 // 0 | 1 | 1
427 // 1 | 1 | -1 (aka 2)
428 // 1 | 0 | <invalid>
429 //
430 // ('s' is for sign, and 'a' is the absolute value.)
431 //
432 // Once bitsliced as such, the following circuits can be used to implement
433 // addition and multiplication mod 3:
434 //
435 // (s3, a3) = (s1, a1) × (s2, a2)
436 // a3 = a1 ∧ a2
437 // s3 = (s1 ⊕ s2) ∧ a3
438 //
439 // (s3, a3) = (s1, a1) + (s2, a2)
440 // t = s1 ⊕ a2
441 // s3 = t ∧ (s2 ⊕ a1)
442 // a3 = (a1 ⊕ a2) ∨ (t ⊕ s2)
443 //
444 // (s3, a3) = (s1, a1) - (s2, a2)
445 // t = a1 ⊕ a2
446 // s3 = (s1 ⊕ a2) ∧ (t ⊕ s2)
447 // a3 = t ∨ (s1 ⊕ s2)
448 //
449 // Negating a value just involves XORing s by a.
450 //
451 // struct poly3 {
452 // struct poly2 s, a;
453 // };
454
455 OPENSSL_UNUSED static void poly3_print(const struct poly3 *in) {
456 struct poly3 p;
457 OPENSSL_memcpy(&p, in, sizeof(p));
458 p.s.v[WORDS_PER_POLY - 1] &= ((crypto_word_t)1 << BITS_IN_LAST_WORD) - 1;
459 p.a.v[WORDS_PER_POLY - 1] &= ((crypto_word_t)1 << BITS_IN_LAST_WORD) - 1;
460
461 printf("{[");
462 for (unsigned i = 0; i < WORDS_PER_POLY; i++) {
463 if (i) {
464 printf(" ");
465 }
466 printf(BN_HEX_FMT2, p.s.v[i]);
467 }
468 printf("] [");
469 for (unsigned i = 0; i < WORDS_PER_POLY; i++) {
470 if (i) {
471 printf(" ");
472 }
473 printf(BN_HEX_FMT2, p.a.v[i]);
474 }
475 printf("]}\n");
476 }
477
478 static void poly3_zero(struct poly3 *p) {
479 poly2_zero(&p->s);
480 poly2_zero(&p->a);
481 }
482
483 // poly3_reverse_700 reverses the order of the first 700 terms of |in| and
484 // writes them to |out|.
485 static void poly3_reverse_700(struct poly3 *out, const struct poly3 *in) {
486 poly2_reverse_700(&out->a, &in->a);
487 poly2_reverse_700(&out->s, &in->s);
488 }
489
490 // poly3_word_mul sets (|out_s|, |out_a|) to (|s1|, |a1|) × (|s2|, |a2|).
491 static void poly3_word_mul(crypto_word_t *out_s, crypto_word_t *out_a,
492 const crypto_word_t s1, const crypto_word_t a1,
493 const crypto_word_t s2, const crypto_word_t a2) {
494 *out_a = a1 & a2;
495 *out_s = (s1 ^ s2) & *out_a;
496 }
497
498 // poly3_word_add sets (|out_s|, |out_a|) to (|s1|, |a1|) + (|s2|, |a2|).
499 static void poly3_word_add(crypto_word_t *out_s, crypto_word_t *out_a,
500 const crypto_word_t s1, const crypto_word_t a1,
501 const crypto_word_t s2, const crypto_word_t a2) {
502 const crypto_word_t t = s1 ^ a2;
503 *out_s = t & (s2 ^ a1);
504 *out_a = (a1 ^ a2) | (t ^ s2);
505 }
506
507 // poly3_word_sub sets (|out_s|, |out_a|) to (|s1|, |a1|) - (|s2|, |a2|).
508 static void poly3_word_sub(crypto_word_t *out_s, crypto_word_t *out_a,
509 const crypto_word_t s1, const crypto_word_t a1,
510 const crypto_word_t s2, const crypto_word_t a2) {
511 const crypto_word_t t = a1 ^ a2;
512 *out_s = (s1 ^ a2) & (t ^ s2);
513 *out_a = t | (s1 ^ s2);
514 }
515
516 // poly3_mul_const sets |p| to |p|×m, where m = (ms, ma).
517 static void poly3_mul_const(struct poly3 *p, crypto_word_t ms,
518 crypto_word_t ma) {
519 ms = lsb_to_all(ms);
520 ma = lsb_to_all(ma);
521
522 for (size_t i = 0; i < WORDS_PER_POLY; i++) {
523 poly3_word_mul(&p->s.v[i], &p->a.v[i], p->s.v[i], p->a.v[i], ms, ma);
524 }
525 }
526
527 // poly3_fmadd sets |out| to |out| - |in|×m, where m is (ms, ma).
528 static void poly3_fmsub(struct poly3 *RESTRICT out,
529 const struct poly3 *RESTRICT in, crypto_word_t ms,
530 crypto_word_t ma) {
531 crypto_word_t product_s, product_a;
532 for (size_t i = 0; i < WORDS_PER_POLY; i++) {
533 poly3_word_mul(&product_s, &product_a, in->s.v[i], in->a.v[i], ms, ma);
534 poly3_word_sub(&out->s.v[i], &out->a.v[i], out->s.v[i], out->a.v[i],
535 product_s, product_a);
536 }
537 }
538
539 // final_bit_to_all replicates the bit in the final position of the last word to
540 // all the bits in the word.
541 static crypto_word_t final_bit_to_all(crypto_word_t v) {
542 return lsb_to_all(v >> (BITS_IN_LAST_WORD - 1));
543 }
544
545 // poly3_top_bits_are_clear returns one iff the extra bits in the final words of
546 // |p| are zero.
547 OPENSSL_UNUSED static int poly3_top_bits_are_clear(const struct poly3 *p) {
548 return poly2_top_bits_are_clear(&p->s) && poly2_top_bits_are_clear(&p->a);
549 }
550
551 // poly3_mod_phiN reduces |p| by Φ(N).
552 static void poly3_mod_phiN(struct poly3 *p) {
553 // In order to reduce by Φ(N) we subtract by the value of the greatest
554 // coefficient.
555 const crypto_word_t factor_s = final_bit_to_all(p->s.v[WORDS_PER_POLY - 1]);
556 const crypto_word_t factor_a = final_bit_to_all(p->a.v[WORDS_PER_POLY - 1]);
557
558 for (size_t i = 0; i < WORDS_PER_POLY; i++) {
559 poly3_word_sub(&p->s.v[i], &p->a.v[i], p->s.v[i], p->a.v[i], factor_s,
560 factor_a);
561 }
562
563 poly2_clear_top_bits(&p->s);
564 poly2_clear_top_bits(&p->a);
565 }
566
567 static void poly3_cswap(struct poly3 *a, struct poly3 *b, crypto_word_t swap) {
568 poly2_cswap(&a->s, &b->s, swap);
569 poly2_cswap(&a->a, &b->a, swap);
570 }
571
572 static void poly3_lshift1(struct poly3 *p) {
573 poly2_lshift1(&p->s);
574 poly2_lshift1(&p->a);
575 }
576
577 static void poly3_rshift1(struct poly3 *p) {
578 poly2_rshift1(&p->s);
579 poly2_rshift1(&p->a);
580 }
581
582 // poly3_span represents a pointer into a poly3.
583 struct poly3_span {
584 crypto_word_t *s;
585 crypto_word_t *a;
586 };
587
588 // poly3_span_add adds |n| words of values from |a| and |b| and writes the
589 // result to |out|.
590 static void poly3_span_add(const struct poly3_span *out,
591 const struct poly3_span *a,
592 const struct poly3_span *b, size_t n) {
593 for (size_t i = 0; i < n; i++) {
594 poly3_word_add(&out->s[i], &out->a[i], a->s[i], a->a[i], b->s[i], b->a[i]);
595 }
596 }
597
598 // poly3_span_sub subtracts |n| words of |b| from |n| words of |a|.
599 static void poly3_span_sub(const struct poly3_span *a,
600 const struct poly3_span *b, size_t n) {
601 for (size_t i = 0; i < n; i++) {
602 poly3_word_sub(&a->s[i], &a->a[i], a->s[i], a->a[i], b->s[i], b->a[i]);
603 }
604 }
605
606 // poly3_mul_aux is a recursive function that multiplies |n| words from |a| and
607 // |b| and writes 2×|n| words to |out|. Each call uses 2*ceil(n/2) elements of
608 // |scratch| and the function recurses, except if |n| == 1, when |scratch| isn't
609 // used and the recursion stops. For |n| in {11, 22}, the transitive total
610 // amount of |scratch| needed happens to be 2n+2.
611 static void poly3_mul_aux(const struct poly3_span *out,
612 const struct poly3_span *scratch,
613 const struct poly3_span *a,
614 const struct poly3_span *b, size_t n) {
615 if (n == 1) {
616 crypto_word_t r_s_low = 0, r_s_high = 0, r_a_low = 0, r_a_high = 0;
617 crypto_word_t b_s = b->s[0], b_a = b->a[0];
618 const crypto_word_t a_s = a->s[0], a_a = a->a[0];
619
620 for (size_t i = 0; i < BITS_PER_WORD; i++) {
621 // Multiply (s, a) by the next value from (b_s, b_a).
622 crypto_word_t m_s, m_a;
623 poly3_word_mul(&m_s, &m_a, a_s, a_a, lsb_to_all(b_s), lsb_to_all(b_a));
624 b_s >>= 1;
625 b_a >>= 1;
626
627 if (i == 0) {
628 // Special case otherwise the code tries to shift by BITS_PER_WORD
629 // below, which is undefined.
630 r_s_low = m_s;
631 r_a_low = m_a;
632 continue;
633 }
634
635 // Shift the multiplication result to the correct position.
636 const crypto_word_t m_s_low = m_s << i;
637 const crypto_word_t m_s_high = m_s >> (BITS_PER_WORD - i);
638 const crypto_word_t m_a_low = m_a << i;
639 const crypto_word_t m_a_high = m_a >> (BITS_PER_WORD - i);
640
641 // Add into the result.
642 poly3_word_add(&r_s_low, &r_a_low, r_s_low, r_a_low, m_s_low, m_a_low);
643 poly3_word_add(&r_s_high, &r_a_high, r_s_high, r_a_high, m_s_high,
644 m_a_high);
645 }
646
647 out->s[0] = r_s_low;
648 out->s[1] = r_s_high;
649 out->a[0] = r_a_low;
650 out->a[1] = r_a_high;
651 return;
652 }
653
654 // Karatsuba multiplication.
655 // https://en.wikipedia.org/wiki/Karatsuba_algorithm
656
657 // When |n| is odd, the two "halves" will have different lengths. The first
658 // is always the smaller.
659 const size_t low_len = n / 2;
660 const size_t high_len = n - low_len;
661 const struct poly3_span a_high = {&a->s[low_len], &a->a[low_len]};
662 const struct poly3_span b_high = {&b->s[low_len], &b->a[low_len]};
663
664 // Store a_1 + a_0 in the first half of |out| and b_1 + b_0 in the second
665 // half.
666 const struct poly3_span a_cross_sum = *out;
667 const struct poly3_span b_cross_sum = {&out->s[high_len], &out->a[high_len]};
668 poly3_span_add(&a_cross_sum, a, &a_high, low_len);
669 poly3_span_add(&b_cross_sum, b, &b_high, low_len);
670 if (high_len != low_len) {
671 a_cross_sum.s[low_len] = a_high.s[low_len];
672 a_cross_sum.a[low_len] = a_high.a[low_len];
673 b_cross_sum.s[low_len] = b_high.s[low_len];
674 b_cross_sum.a[low_len] = b_high.a[low_len];
675 }
676
677 const struct poly3_span child_scratch = {&scratch->s[2 * high_len],
678 &scratch->a[2 * high_len]};
679 const struct poly3_span out_mid = {&out->s[low_len], &out->a[low_len]};
680 const struct poly3_span out_high = {&out->s[2 * low_len],
681 &out->a[2 * low_len]};
682
683 // Calculate (a_1 + a_0) × (b_1 + b_0) and write to scratch buffer.
684 poly3_mul_aux(scratch, &child_scratch, &a_cross_sum, &b_cross_sum, high_len);
685 // Calculate a_1 × b_1.
686 poly3_mul_aux(&out_high, &child_scratch, &a_high, &b_high, high_len);
687 // Calculate a_0 × b_0.
688 poly3_mul_aux(out, &child_scratch, a, b, low_len);
689
690 // Subtract those last two products from the first.
691 poly3_span_sub(scratch, out, low_len * 2);
692 poly3_span_sub(scratch, &out_high, high_len * 2);
693
694 // Add the middle product into the output.
695 poly3_span_add(&out_mid, &out_mid, scratch, high_len * 2);
696 }
697
698 // HRSS_poly3_mul sets |*out| to |x|×|y| mod Φ(N).
699 void HRSS_poly3_mul(struct poly3 *out, const struct poly3 *x,
700 const struct poly3 *y) {
701 crypto_word_t prod_s[WORDS_PER_POLY * 2];
702 crypto_word_t prod_a[WORDS_PER_POLY * 2];
703 crypto_word_t scratch_s[WORDS_PER_POLY * 2 + 2];
704 crypto_word_t scratch_a[WORDS_PER_POLY * 2 + 2];
705 const struct poly3_span prod_span = {prod_s, prod_a};
706 const struct poly3_span scratch_span = {scratch_s, scratch_a};
707 const struct poly3_span x_span = {(crypto_word_t *)x->s.v,
708 (crypto_word_t *)x->a.v};
709 const struct poly3_span y_span = {(crypto_word_t *)y->s.v,
710 (crypto_word_t *)y->a.v};
711
712 poly3_mul_aux(&prod_span, &scratch_span, &x_span, &y_span, WORDS_PER_POLY);
713
714 // |prod| needs to be reduced mod (𝑥^n - 1), which just involves adding the
715 // upper-half to the lower-half. However, N is 701, which isn't a multiple of
716 // BITS_PER_WORD, so the upper-half vectors all have to be shifted before
717 // being added to the lower-half.
718 for (size_t i = 0; i < WORDS_PER_POLY; i++) {
719 crypto_word_t v_s = prod_s[WORDS_PER_POLY + i - 1] >> BITS_IN_LAST_WORD;
720 v_s |= prod_s[WORDS_PER_POLY + i] << (BITS_PER_WORD - BITS_IN_LAST_WORD);
721 crypto_word_t v_a = prod_a[WORDS_PER_POLY + i - 1] >> BITS_IN_LAST_WORD;
722 v_a |= prod_a[WORDS_PER_POLY + i] << (BITS_PER_WORD - BITS_IN_LAST_WORD);
723
724 poly3_word_add(&out->s.v[i], &out->a.v[i], prod_s[i], prod_a[i], v_s, v_a);
725 }
726
727 poly3_mod_phiN(out);
728 }
729
730 #if defined(HRSS_HAVE_VECTOR_UNIT) && !defined(OPENSSL_AARCH64)
731
732 // poly3_vec_cswap swaps (|a_s|, |a_a|) and (|b_s|, |b_a|) if |swap| is
733 // |0xff..ff|. Otherwise, |swap| must be zero.
734 static inline void poly3_vec_cswap(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6],
735 vec_t b_a[6], const vec_t swap) {
736 for (int i = 0; i < 6; i++) {
737 const vec_t sum_s = swap & (a_s[i] ^ b_s[i]);
738 a_s[i] ^= sum_s;
739 b_s[i] ^= sum_s;
740
741 const vec_t sum_a = swap & (a_a[i] ^ b_a[i]);
742 a_a[i] ^= sum_a;
743 b_a[i] ^= sum_a;
744 }
745 }
746
747 // poly3_vec_fmsub subtracts (|ms|, |ma|) × (|b_s|, |b_a|) from (|a_s|, |a_a|).
748 static inline void poly3_vec_fmsub(vec_t a_s[6], vec_t a_a[6], vec_t b_s[6],
749 vec_t b_a[6], const vec_t ms,
750 const vec_t ma) {
751 for (int i = 0; i < 6; i++) {
752 // See the bitslice formula, above.
753 const vec_t s = b_s[i];
754 const vec_t a = b_a[i];
755 const vec_t product_a = a & ma;
756 const vec_t product_s = (s ^ ms) & product_a;
757
758 const vec_t out_s = a_s[i];
759 const vec_t out_a = a_a[i];
760 const vec_t t = out_a ^ product_a;
761 a_s[i] = (out_s ^ product_a) & (t ^ product_s);
762 a_a[i] = t | (out_s ^ product_s);
763 }
764 }
765
766 // poly3_invert_vec sets |*out| to |in|^-1, i.e. such that |out|×|in| == 1 mod
767 // Φ(N).
768 static void poly3_invert_vec(struct poly3 *out, const struct poly3 *in) {
769 // This algorithm is taken from section 7.1 of [SAFEGCD].
770 const vec_t kZero = {0};
771 const vec_t kOne = {1};
772 static const uint8_t kBottomSixtyOne[sizeof(vec_t)] = {
773 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f};
774
775 vec_t v_s[6], v_a[6], r_s[6], r_a[6], f_s[6], f_a[6], g_s[6], g_a[6];
776 // v = 0
777 memset(&v_s, 0, sizeof(v_s));
778 memset(&v_a, 0, sizeof(v_a));
779 // r = 1
780 memset(&r_s, 0, sizeof(r_s));
781 memset(&r_a, 0, sizeof(r_a));
782 r_a[0] = kOne;
783 // f = all ones.
784 memset(f_s, 0, sizeof(f_s));
785 memset(f_a, 0xff, 5 * sizeof(vec_t));
786 memcpy(&f_a[5], kBottomSixtyOne, sizeof(kBottomSixtyOne));
787 // g is the reversal of |in|.
788 struct poly3 in_reversed;
789 poly3_reverse_700(&in_reversed, in);
790 g_s[5] = kZero;
791 memcpy(&g_s, &in_reversed.s.v, WORDS_PER_POLY * sizeof(crypto_word_t));
792 g_a[5] = kZero;
793 memcpy(&g_a, &in_reversed.a.v, WORDS_PER_POLY * sizeof(crypto_word_t));
794
795 int delta = 1;
796
797 for (size_t i = 0; i < (2*(N-1)) - 1; i++) {
798 poly3_vec_lshift1(v_s, v_a);
799
800 const crypto_word_t delta_sign_bit = (delta >> (sizeof(delta) * 8 - 1)) & 1;
801 const crypto_word_t delta_is_non_negative = delta_sign_bit - 1;
802 const crypto_word_t delta_is_non_zero = ~constant_time_is_zero_w(delta);
803 const vec_t g_has_constant_term = vec_broadcast_bit(g_a[0]);
804 const vec_t mask_w =
805 {delta_is_non_negative & delta_is_non_zero};
806 const vec_t mask = vec_broadcast_bit(mask_w) & g_has_constant_term;
807
808 const vec_t c_a = vec_broadcast_bit(f_a[0] & g_a[0]);
809 const vec_t c_s = vec_broadcast_bit((f_s[0] ^ g_s[0]) & c_a);
810
811 // SSE2 is an Intel thing. So, checking for |OPENSSL_SSE2| should avoid
812 // hitting the Arm specific path under the #else.
813 #if defined(OPENSSL_SSE2)
814 // This is necessary because older versions of GCC, such as version 4.1.2,
815 // do not support accessing individual elements of the __m128i type
816 alignas(16) uint64_t mask_tmp[2];
817 _mm_store_si128((void*) mask_tmp, mask);
818 delta = constant_time_select_int(lsb_to_all(mask_tmp[0]), -delta, delta);
819 #else
820 delta = constant_time_select_int(lsb_to_all(mask[0]), -delta, delta);
821 #endif
822 delta++;
823
824 poly3_vec_cswap(f_s, f_a, g_s, g_a, mask);
825 poly3_vec_fmsub(g_s, g_a, f_s, f_a, c_s, c_a);
826 poly3_vec_rshift1(g_s, g_a);
827
828 poly3_vec_cswap(v_s, v_a, r_s, r_a, mask);
829 poly3_vec_fmsub(r_s, r_a, v_s, v_a, c_s, c_a);
830 }
831
832 assert(delta == 0);
833 memcpy(out->s.v, v_s, WORDS_PER_POLY * sizeof(crypto_word_t));
834 memcpy(out->a.v, v_a, WORDS_PER_POLY * sizeof(crypto_word_t));
835 poly3_mul_const(out, vec_get_word(f_s[0], 0), vec_get_word(f_a[0], 0));
836 poly3_reverse_700(out, out);
837 }
838
839 #endif // HRSS_HAVE_VECTOR_UNIT
840
841 // HRSS_poly3_invert sets |*out| to |in|^-1, i.e. such that |out|×|in| == 1 mod
842 // Φ(N).
843 void HRSS_poly3_invert(struct poly3 *out, const struct poly3 *in) {
844 // The vector version of this function seems slightly slower on AArch64, but
845 // is useful on ARMv7 and x86-64.
846 #if defined(HRSS_HAVE_VECTOR_UNIT) && !defined(OPENSSL_AARCH64)
847 if (vec_capable()) {
848 poly3_invert_vec(out, in);
849 return;
850 }
851 #endif
852
853 // This algorithm is taken from section 7.1 of [SAFEGCD].
854 struct poly3 v, r, f, g;
855 // v = 0
856 poly3_zero(&v);
857 // r = 1
858 poly3_zero(&r);
859 r.a.v[0] = 1;
860 // f = all ones.
861 OPENSSL_memset(&f.s, 0, sizeof(struct poly2));
862 OPENSSL_memset(&f.a, 0xff, sizeof(struct poly2));
863 f.a.v[WORDS_PER_POLY - 1] >>= BITS_PER_WORD - BITS_IN_LAST_WORD;
864 // g is the reversal of |in|.
865 poly3_reverse_700(&g, in);
866 int delta = 1;
867
868 for (size_t i = 0; i < (2*(N-1)) - 1; i++) {
869 poly3_lshift1(&v);
870
871 const crypto_word_t delta_sign_bit = (delta >> (sizeof(delta) * 8 - 1)) & 1;
872 const crypto_word_t delta_is_non_negative = delta_sign_bit - 1;
873 const crypto_word_t delta_is_non_zero = ~constant_time_is_zero_w(delta);
874 const crypto_word_t g_has_constant_term = lsb_to_all(g.a.v[0]);
875 const crypto_word_t mask =
876 g_has_constant_term & delta_is_non_negative & delta_is_non_zero;
877
878 crypto_word_t c_s, c_a;
879 poly3_word_mul(&c_s, &c_a, f.s.v[0], f.a.v[0], g.s.v[0], g.a.v[0]);
880 c_s = lsb_to_all(c_s);
881 c_a = lsb_to_all(c_a);
882
883 delta = constant_time_select_int(mask, -delta, delta);
884 delta++;
885
886 poly3_cswap(&f, &g, mask);
887 poly3_fmsub(&g, &f, c_s, c_a);
888 poly3_rshift1(&g);
889
890 poly3_cswap(&v, &r, mask);
891 poly3_fmsub(&r, &v, c_s, c_a);
892 }
893
894 assert(delta == 0);
895 poly3_mul_const(&v, f.s.v[0], f.a.v[0]);
896 poly3_reverse_700(out, &v);
897 }
898
899 // Polynomials in Q.
900
901 // Coefficients are reduced mod Q. (Q is clearly not prime, therefore the
902 // coefficients do not form a field.)
903 #define Q 8192
904
905 // VECS_PER_POLY is the number of 128-bit vectors needed to represent a
906 // polynomial.
907 #define COEFFICIENTS_PER_VEC (sizeof(vec_t) / sizeof(uint16_t))
908 #define VECS_PER_POLY ((N + COEFFICIENTS_PER_VEC - 1) / COEFFICIENTS_PER_VEC)
909
910 // poly represents a polynomial with coefficients mod Q. Note that, while Q is a
911 // power of two, this does not operate in GF(Q). That would be a binary field
912 // but this is simply mod Q. Thus the coefficients are not a field.
913 //
914 // Coefficients are ordered little-endian, thus the coefficient of x^0 is the
915 // first element of the array.
916 struct poly {
917 alignas(16) uint16_t v[N+3];
918 };
919
920 #if defined(HRSS_HAVE_VECTOR_UNIT)
921 struct poly_vec {
922 // N + 3 = 704, which is a multiple of 64 and thus aligns things, esp for
923 // the vector code.
924 vec_t vectors[VECS_PER_POLY];
925 };
926
927 static void poly_vec2poly(struct poly *p, const struct poly_vec *pv)
928 {
929 OPENSSL_memcpy(p, pv, sizeof(*p));
930 }
931 static void poly2poly_vec(struct poly_vec *pv, const struct poly *p)
932 {
933 OPENSSL_memcpy(pv, p, sizeof(*p));
934 }
935 #endif
936
937 // poly_normalize zeros out the excess elements of |x| which are included only
938 // for alignment.
939 static void poly_normalize(struct poly *x) {
940 OPENSSL_memset(&x->v[N], 0, 3 * sizeof(uint16_t));
941 }
942
943 // poly_assert_normalized asserts that the excess elements of |x| are zeroed out
944 // for the cases that case. (E.g. |poly_mul_vec|.)
945 static void poly_assert_normalized(const struct poly *x) {
946 assert(x->v[N] == 0);
947 assert(x->v[N + 1] == 0);
948 assert(x->v[N + 2] == 0);
949 }
950
951 OPENSSL_UNUSED static void poly_print(const struct poly *p) {
952 printf("[");
953 for (unsigned i = 0; i < N; i++) {
954 if (i) {
955 printf(" ");
956 }
957 printf("%d", p->v[i]);
958 }
959 printf("]\n");
960 }
961
962 // POLY_MUL_SCRATCH contains space for the working variables needed by
963 // |poly_mul|. The contents afterwards may be discarded, but the object may also
964 // be reused with future |poly_mul| calls to save heap allocations.
965 //
966 // This object must have 32-byte alignment.
967 struct POLY_MUL_SCRATCH {
968 union {
969 // This is used by |poly_mul_novec|.
970 struct {
971 uint16_t prod[2 * N];
972 uint16_t scratch[1318];
973 } novec;
974
975 #if defined(HRSS_HAVE_VECTOR_UNIT)
976 // This is used by |poly_mul_vec|.
977 struct {
978 vec_t prod[VECS_PER_POLY * 2];
979 vec_t scratch[172];
980 } vec;
981 #endif
982
983 #if defined(POLY_RQ_MUL_ASM)
984 // This is the space used by |poly_Rq_mul|.
985 uint8_t rq[POLY_MUL_RQ_SCRATCH_SPACE];
986 #endif
987 } u;
988 };
989
990 #if defined(HRSS_HAVE_VECTOR_UNIT)
991
992 // poly_mul_vec_aux is a recursive function that multiplies |n| words from |a|
993 // and |b| and writes 2×|n| words to |out|. Each call uses 2*ceil(n/2) elements
994 // of |scratch| and the function recurses, except if |n| < 3, when |scratch|
995 // isn't used and the recursion stops. If |n| == |VECS_PER_POLY| then |scratch|
996 // needs 172 elements.
997 static void poly_mul_vec_aux(vec_t *restrict out, vec_t *restrict scratch,
998 const vec_t *restrict a, const vec_t *restrict b,
999 const size_t n) {
1000 // In [HRSS], the technique they used for polynomial multiplication is
1001 // described: they start with Toom-4 at the top level and then two layers of
1002 // Karatsuba. Karatsuba is a specific instance of the general Toom–Cook
1003 // decomposition, which splits an input n-ways and produces 2n-1
1004 // multiplications of those parts. So, starting with 704 coefficients (rounded
1005 // up from 701 to have more factors of two), Toom-4 gives seven
1006 // multiplications of degree-174 polynomials. Each round of Karatsuba (which
1007 // is Toom-2) increases the number of multiplications by a factor of three
1008 // while halving the size of the values being multiplied. So two rounds gives
1009 // 63 multiplications of degree-44 polynomials. Then they (I think) form
1010 // vectors by gathering all 63 coefficients of each power together, for each
1011 // input, and doing more rounds of Karatsuba on the vectors until they bottom-
1012 // out somewhere with schoolbook multiplication.
1013 //
1014 // I tried something like that for NEON. NEON vectors are 128 bits so hold
1015 // eight coefficients. I wrote a function that did Karatsuba on eight
1016 // multiplications at the same time, using such vectors, and a Go script that
1017 // decomposed from degree-704, with Karatsuba in non-transposed form, until it
1018 // reached multiplications of degree-44. It batched up those 81
1019 // multiplications into lots of eight with a single one left over (which was
1020 // handled directly).
1021 //
1022 // It worked, but it was significantly slower than the dumb algorithm used
1023 // below. Potentially that was because I misunderstood how [HRSS] did it, or
1024 // because Clang is bad at generating good code from NEON intrinsics on ARMv7.
1025 // (Which is true: the code generated by Clang for the below is pretty crap.)
1026 //
1027 // This algorithm is much simpler. It just does Karatsuba decomposition all
1028 // the way down and never transposes. When it gets down to degree-16 or
1029 // degree-24 values, they are multiplied using schoolbook multiplication and
1030 // vector intrinsics. The vector operations form each of the eight phase-
1031 // shifts of one of the inputs, point-wise multiply, and then add into the
1032 // result at the correct place. This means that 33% (degree-16) or 25%
1033 // (degree-24) of the multiplies and adds are wasted, but it does ok.
1034 if (n == 2) {
1035 vec_t result[4];
1036 vec_t vec_a[3];
1037 static const vec_t kZero = {0};
1038 vec_a[0] = a[0];
1039 vec_a[1] = a[1];
1040 vec_a[2] = kZero;
1041
1042 result[0] = vec_mul(vec_a[0], vec_get_word(b[0], 0));
1043 result[1] = vec_mul(vec_a[1], vec_get_word(b[0], 0));
1044
1045 result[1] = vec_fma(result[1], vec_a[0], vec_get_word(b[1], 0));
1046 result[2] = vec_mul(vec_a[1], vec_get_word(b[1], 0));
1047 result[3] = kZero;
1048
1049 vec3_rshift_word(vec_a);
1050
1051 #define BLOCK(x, y) \
1052 do { \
1053 result[x + 0] = \
1054 vec_fma(result[x + 0], vec_a[0], vec_get_word(b[y / 8], y % 8)); \
1055 result[x + 1] = \
1056 vec_fma(result[x + 1], vec_a[1], vec_get_word(b[y / 8], y % 8)); \
1057 result[x + 2] = \
1058 vec_fma(result[x + 2], vec_a[2], vec_get_word(b[y / 8], y % 8)); \
1059 } while (0)
1060
1061 BLOCK(0, 1);
1062 BLOCK(1, 9);
1063
1064 vec3_rshift_word(vec_a);
1065
1066 BLOCK(0, 2);
1067 BLOCK(1, 10);
1068
1069 vec3_rshift_word(vec_a);
1070
1071 BLOCK(0, 3);
1072 BLOCK(1, 11);
1073
1074 vec3_rshift_word(vec_a);
1075
1076 BLOCK(0, 4);
1077 BLOCK(1, 12);
1078
1079 vec3_rshift_word(vec_a);
1080
1081 BLOCK(0, 5);
1082 BLOCK(1, 13);
1083
1084 vec3_rshift_word(vec_a);
1085
1086 BLOCK(0, 6);
1087 BLOCK(1, 14);
1088
1089 vec3_rshift_word(vec_a);
1090
1091 BLOCK(0, 7);
1092 BLOCK(1, 15);
1093
1094 #undef BLOCK
1095
1096 memcpy(out, result, sizeof(result));
1097 return;
1098 }
1099
1100 if (n == 3) {
1101 vec_t result[6];
1102 vec_t vec_a[4];
1103 static const vec_t kZero = {0};
1104 vec_a[0] = a[0];
1105 vec_a[1] = a[1];
1106 vec_a[2] = a[2];
1107 vec_a[3] = kZero;
1108
1109 result[0] = vec_mul(a[0], vec_get_word(b[0], 0));
1110 result[1] = vec_mul(a[1], vec_get_word(b[0], 0));
1111 result[2] = vec_mul(a[2], vec_get_word(b[0], 0));
1112
1113 #define BLOCK_PRE(x, y) \
1114 do { \
1115 result[x + 0] = \
1116 vec_fma(result[x + 0], vec_a[0], vec_get_word(b[y / 8], y % 8)); \
1117 result[x + 1] = \
1118 vec_fma(result[x + 1], vec_a[1], vec_get_word(b[y / 8], y % 8)); \
1119 result[x + 2] = vec_mul(vec_a[2], vec_get_word(b[y / 8], y % 8)); \
1120 } while (0)
1121
1122 BLOCK_PRE(1, 8);
1123 BLOCK_PRE(2, 16);
1124
1125 result[5] = kZero;
1126
1127 vec4_rshift_word(vec_a);
1128
1129 #define BLOCK(x, y) \
1130 do { \
1131 result[x + 0] = \
1132 vec_fma(result[x + 0], vec_a[0], vec_get_word(b[y / 8], y % 8)); \
1133 result[x + 1] = \
1134 vec_fma(result[x + 1], vec_a[1], vec_get_word(b[y / 8], y % 8)); \
1135 result[x + 2] = \
1136 vec_fma(result[x + 2], vec_a[2], vec_get_word(b[y / 8], y % 8)); \
1137 result[x + 3] = \
1138 vec_fma(result[x + 3], vec_a[3], vec_get_word(b[y / 8], y % 8)); \
1139 } while (0)
1140
1141 BLOCK(0, 1);
1142 BLOCK(1, 9);
1143 BLOCK(2, 17);
1144
1145 vec4_rshift_word(vec_a);
1146
1147 BLOCK(0, 2);
1148 BLOCK(1, 10);
1149 BLOCK(2, 18);
1150
1151 vec4_rshift_word(vec_a);
1152
1153 BLOCK(0, 3);
1154 BLOCK(1, 11);
1155 BLOCK(2, 19);
1156
1157 vec4_rshift_word(vec_a);
1158
1159 BLOCK(0, 4);
1160 BLOCK(1, 12);
1161 BLOCK(2, 20);
1162
1163 vec4_rshift_word(vec_a);
1164
1165 BLOCK(0, 5);
1166 BLOCK(1, 13);
1167 BLOCK(2, 21);
1168
1169 vec4_rshift_word(vec_a);
1170
1171 BLOCK(0, 6);
1172 BLOCK(1, 14);
1173 BLOCK(2, 22);
1174
1175 vec4_rshift_word(vec_a);
1176
1177 BLOCK(0, 7);
1178 BLOCK(1, 15);
1179 BLOCK(2, 23);
1180
1181 #undef BLOCK
1182 #undef BLOCK_PRE
1183
1184 memcpy(out, result, sizeof(result));
1185
1186 return;
1187 }
1188
1189 // Karatsuba multiplication.
1190 // https://en.wikipedia.org/wiki/Karatsuba_algorithm
1191
1192 // When |n| is odd, the two "halves" will have different lengths. The first is
1193 // always the smaller.
1194 const size_t low_len = n / 2;
1195 const size_t high_len = n - low_len;
1196 const vec_t *a_high = &a[low_len];
1197 const vec_t *b_high = &b[low_len];
1198
1199 // Store a_1 + a_0 in the first half of |out| and b_1 + b_0 in the second
1200 // half.
1201 for (size_t i = 0; i < low_len; i++) {
1202 out[i] = vec_add(a_high[i], a[i]);
1203 out[high_len + i] = vec_add(b_high[i], b[i]);
1204 }
1205 if (high_len != low_len) {
1206 out[low_len] = a_high[low_len];
1207 out[high_len + low_len] = b_high[low_len];
1208 }
1209
1210 vec_t *const child_scratch = &scratch[2 * high_len];
1211 // Calculate (a_1 + a_0) × (b_1 + b_0) and write to scratch buffer.
1212 poly_mul_vec_aux(scratch, child_scratch, out, &out[high_len], high_len);
1213 // Calculate a_1 × b_1.
1214 poly_mul_vec_aux(&out[low_len * 2], child_scratch, a_high, b_high, high_len);
1215 // Calculate a_0 × b_0.
1216 poly_mul_vec_aux(out, child_scratch, a, b, low_len);
1217
1218 // Subtract those last two products from the first.
1219 for (size_t i = 0; i < low_len * 2; i++) {
1220 scratch[i] = vec_sub(scratch[i], vec_add(out[i], out[low_len * 2 + i]));
1221 }
1222 if (low_len != high_len) {
1223 scratch[low_len * 2] = vec_sub(scratch[low_len * 2], out[low_len * 4]);
1224 scratch[low_len * 2 + 1] =
1225 vec_sub(scratch[low_len * 2 + 1], out[low_len * 4 + 1]);
1226 }
1227
1228 // Add the middle product into the output.
1229 for (size_t i = 0; i < high_len * 2; i++) {
1230 out[low_len + i] = vec_add(out[low_len + i], scratch[i]);
1231 }
1232 }
1233
1234 // poly_mul_vec sets |*out| to |x|×|y| mod (𝑥^n - 1).
1235 static void poly_mul_vec(struct POLY_MUL_SCRATCH *scratch, struct poly *out,
1236 const struct poly *x, const struct poly *y) {
1237 OPENSSL_STATIC_ASSERT(sizeof(out->v) == sizeof(vec_t) * VECS_PER_POLY,
1238 struct_poly_is_the_wrong_size)
1239 OPENSSL_STATIC_ASSERT(alignof(struct poly) == alignof(vec_t),
1240 struct_poly_has_incorrect_alignment)
1241
1242 poly_assert_normalized(x);
1243 poly_assert_normalized(y);
1244
1245 struct poly_vec x_vec = {{{0}}};
1246 struct poly_vec y_vec = {{{0}}};
1247 poly2poly_vec(&x_vec, x);
1248 poly2poly_vec(&y_vec, y);
1249
1250 vec_t *const prod = scratch->u.vec.prod;
1251 vec_t *const aux_scratch = scratch->u.vec.scratch;
1252 poly_mul_vec_aux(prod, aux_scratch, x_vec.vectors, y_vec.vectors, VECS_PER_POLY);
1253
1254 // |prod| needs to be reduced mod (𝑥^n - 1), which just involves adding the
1255 // upper-half to the lower-half. However, N is 701, which isn't a multiple of
1256 // the vector size, so the upper-half vectors all have to be shifted before
1257 // being added to the lower-half.
1258 struct poly_vec out_vecs = {{{0}}};
1259
1260 for (size_t i = 0; i < VECS_PER_POLY; i++) {
1261 const vec_t prev = prod[VECS_PER_POLY - 1 + i];
1262 const vec_t this = prod[VECS_PER_POLY + i];
1263 out_vecs.vectors[i] = vec_add(prod[i], vec_merge_3_5(prev, this));
1264 }
1265
1266 poly_vec2poly(out, &out_vecs);
1267 OPENSSL_memset(&out->v[N], 0, 3 * sizeof(uint16_t));
1268 }
1269
1270 #endif // HRSS_HAVE_VECTOR_UNIT
1271
1272 // poly_mul_novec_aux writes the product of |a| and |b| to |out|, using
1273 // |scratch| as scratch space. It'll use Karatsuba if the inputs are large
1274 // enough to warrant it. Each call uses 2*ceil(n/2) elements of |scratch| and
1275 // the function recurses, except if |n| < 64, when |scratch| isn't used and the
1276 // recursion stops. If |n| == |N| then |scratch| needs 1318 elements.
1277 static void poly_mul_novec_aux(uint16_t *out, uint16_t *scratch,
1278 const uint16_t *a, const uint16_t *b, size_t n) {
1279 static const size_t kSchoolbookLimit = 64;
1280 if (n < kSchoolbookLimit) {
1281 OPENSSL_memset(out, 0, sizeof(uint16_t) * n * 2);
1282 for (size_t i = 0; i < n; i++) {
1283 for (size_t j = 0; j < n; j++) {
1284 out[i + j] += (unsigned) a[i] * b[j];
1285 }
1286 }
1287
1288 return;
1289 }
1290
1291 // Karatsuba multiplication.
1292 // https://en.wikipedia.org/wiki/Karatsuba_algorithm
1293
1294 // When |n| is odd, the two "halves" will have different lengths. The
1295 // first is always the smaller.
1296 const size_t low_len = n / 2;
1297 const size_t high_len = n - low_len;
1298 const uint16_t *const a_high = &a[low_len];
1299 const uint16_t *const b_high = &b[low_len];
1300
1301 for (size_t i = 0; i < low_len; i++) {
1302 out[i] = a_high[i] + a[i];
1303 out[high_len + i] = b_high[i] + b[i];
1304 }
1305 if (high_len != low_len) {
1306 out[low_len] = a_high[low_len];
1307 out[high_len + low_len] = b_high[low_len];
1308 }
1309
1310 uint16_t *const child_scratch = &scratch[2 * high_len];
1311 poly_mul_novec_aux(scratch, child_scratch, out, &out[high_len], high_len);
1312 poly_mul_novec_aux(&out[low_len * 2], child_scratch, a_high, b_high,
1313 high_len);
1314 poly_mul_novec_aux(out, child_scratch, a, b, low_len);
1315
1316 for (size_t i = 0; i < low_len * 2; i++) {
1317 scratch[i] -= out[i] + out[low_len * 2 + i];
1318 }
1319 if (low_len != high_len) {
1320 scratch[low_len * 2] -= out[low_len * 4];
1321 assert(out[low_len * 4 + 1] == 0);
1322 }
1323
1324 for (size_t i = 0; i < high_len * 2; i++) {
1325 out[low_len + i] += scratch[i];
1326 }
1327 }
1328
1329 // poly_mul_novec sets |*out| to |x|×|y| mod (𝑥^n - 1).
1330 static void poly_mul_novec(struct POLY_MUL_SCRATCH *scratch, struct poly *out,
1331 const struct poly *x, const struct poly *y) {
1332 uint16_t *const prod = scratch->u.novec.prod;
1333 uint16_t *const aux_scratch = scratch->u.novec.scratch;
1334 poly_mul_novec_aux(prod, aux_scratch, x->v, y->v, N);
1335
1336 for (size_t i = 0; i < N; i++) {
1337 out->v[i] = prod[i] + prod[i + N];
1338 }
1339 OPENSSL_memset(&out->v[N], 0, 3 * sizeof(uint16_t));
1340 }
1341
1342 static void poly_mul(struct POLY_MUL_SCRATCH *scratch, struct poly *r,
1343 const struct poly *a, const struct poly *b) {
1344 #if defined(POLY_RQ_MUL_ASM)
1345 if (CRYPTO_is_AVX2_capable()) {
1346 poly_Rq_mul(r->v, a->v, b->v, scratch->u.rq);
1347 poly_normalize(r);
1348 } else
1349 #endif
1350
1351 #if defined(HRSS_HAVE_VECTOR_UNIT)
1352 if (vec_capable()) {
1353 poly_mul_vec(scratch, r, a, b);
1354 } else
1355 #endif
1356
1357 // Fallback, non-vector case.
1358 {
1359 poly_mul_novec(scratch, r, a, b);
1360 }
1361
1362 poly_assert_normalized(r);
1363 }
1364
1365 // poly_mul_x_minus_1 sets |p| to |p|×(𝑥 - 1) mod (𝑥^n - 1).
1366 static void poly_mul_x_minus_1(struct poly *p) {
1367 // Multiplying by (𝑥 - 1) means negating each coefficient and adding in
1368 // the value of the previous one.
1369 const uint16_t orig_final_coefficient = p->v[N - 1];
1370
1371 for (size_t i = N - 1; i > 0; i--) {
1372 p->v[i] = p->v[i - 1] - p->v[i];
1373 }
1374 p->v[0] = orig_final_coefficient - p->v[0];
1375 }
1376
1377 // poly_mod_phiN sets |p| to |p| mod Φ(N).
1378 static void poly_mod_phiN(struct poly *p) {
1379 const uint16_t coeff700 = p->v[N - 1];
1380
1381 for (unsigned i = 0; i < N; i++) {
1382 p->v[i] -= coeff700;
1383 }
1384 }
1385
1386 // poly_clamp reduces each coefficient mod Q.
1387 static void poly_clamp(struct poly *p) {
1388 for (unsigned i = 0; i < N; i++) {
1389 p->v[i] &= Q - 1;
1390 }
1391 }
1392
1393
1394 // Conversion functions
1395 // --------------------
1396
1397 // poly2_from_poly sets |*out| to |in| mod 2.
1398 static void poly2_from_poly(struct poly2 *out, const struct poly *in) {
1399 crypto_word_t *words = out->v;
1400 unsigned shift = 0;
1401 crypto_word_t word = 0;
1402
1403 for (unsigned i = 0; i < N; i++) {
1404 word >>= 1;
1405 word |= (crypto_word_t)(in->v[i] & 1) << (BITS_PER_WORD - 1);
1406 shift++;
1407
1408 if (shift == BITS_PER_WORD) {
1409 *words = word;
1410 words++;
1411 word = 0;
1412 shift = 0;
1413 }
1414 }
1415
1416 word >>= BITS_PER_WORD - shift;
1417 *words = word;
1418 }
1419
1420 // mod3 treats |a| as a signed number and returns |a| mod 3.
1421 static uint16_t mod3(int16_t a) {
1422 const int16_t q = ((int32_t)a * 21845) >> 16;
1423 int16_t ret = a - 3 * q;
1424 // At this point, |ret| is in {0, 1, 2, 3} and that needs to be mapped to {0,
1425 // 1, 2, 0}.
1426 return ret & ((ret & (ret >> 1)) - 1);
1427 }
1428
1429 // poly3_from_poly sets |*out| to |in|.
1430 static void poly3_from_poly(struct poly3 *out, const struct poly *in) {
1431 crypto_word_t *words_s = out->s.v;
1432 crypto_word_t *words_a = out->a.v;
1433 crypto_word_t s = 0;
1434 crypto_word_t a = 0;
1435 unsigned shift = 0;
1436
1437 for (unsigned i = 0; i < N; i++) {
1438 // This duplicates the 13th bit upwards to the top of the uint16,
1439 // essentially treating it as a sign bit and converting into a signed int16.
1440 // The signed value is reduced mod 3, yielding {0, 1, 2}.
1441 const uint16_t v = mod3((int16_t)(in->v[i] << 3) >> 3);
1442 s >>= 1;
1443 const crypto_word_t s_bit = (crypto_word_t)(v & 2) << (BITS_PER_WORD - 2);
1444 s |= s_bit;
1445 a >>= 1;
1446 a |= s_bit | (crypto_word_t)(v & 1) << (BITS_PER_WORD - 1);
1447 shift++;
1448
1449 if (shift == BITS_PER_WORD) {
1450 *words_s = s;
1451 words_s++;
1452 *words_a = a;
1453 words_a++;
1454 s = a = 0;
1455 shift = 0;
1456 }
1457 }
1458
1459 s >>= BITS_PER_WORD - shift;
1460 a >>= BITS_PER_WORD - shift;
1461 *words_s = s;
1462 *words_a = a;
1463 }
1464
1465 // poly3_from_poly_checked sets |*out| to |in|, which has coefficients in {0, 1,
1466 // Q-1}. It returns a mask indicating whether all coefficients were found to be
1467 // in that set.
1468 static crypto_word_t poly3_from_poly_checked(struct poly3 *out,
1469 const struct poly *in) {
1470 crypto_word_t *words_s = out->s.v;
1471 crypto_word_t *words_a = out->a.v;
1472 crypto_word_t s = 0;
1473 crypto_word_t a = 0;
1474 unsigned shift = 0;
1475 crypto_word_t ok = CONSTTIME_TRUE_W;
1476
1477 for (unsigned i = 0; i < N; i++) {
1478 const uint16_t v = in->v[i];
1479 // Maps {0, 1, Q-1} to {0, 1, 2}.
1480 uint16_t mod3 = v & 3;
1481 mod3 ^= mod3 >> 1;
1482 const uint16_t expected = (uint16_t)((~((mod3 >> 1) - 1)) | mod3) % Q;
1483 ok &= constant_time_eq_w(v, expected);
1484
1485 s >>= 1;
1486 const crypto_word_t s_bit = (crypto_word_t)(mod3 & 2)
1487 << (BITS_PER_WORD - 2);
1488 s |= s_bit;
1489 a >>= 1;
1490 a |= s_bit | (crypto_word_t)(mod3 & 1) << (BITS_PER_WORD - 1);
1491 shift++;
1492
1493 if (shift == BITS_PER_WORD) {
1494 *words_s = s;
1495 words_s++;
1496 *words_a = a;
1497 words_a++;
1498 s = a = 0;
1499 shift = 0;
1500 }
1501 }
1502
1503 s >>= BITS_PER_WORD - shift;
1504 a >>= BITS_PER_WORD - shift;
1505 *words_s = s;
1506 *words_a = a;
1507
1508 return ok;
1509 }
1510
1511 static void poly_from_poly2(struct poly *out, const struct poly2 *in) {
1512 const crypto_word_t *words = in->v;
1513 unsigned shift = 0;
1514 crypto_word_t word = *words;
1515
1516 for (unsigned i = 0; i < N; i++) {
1517 out->v[i] = word & 1;
1518 word >>= 1;
1519 shift++;
1520
1521 if (shift == BITS_PER_WORD) {
1522 words++;
1523 word = *words;
1524 shift = 0;
1525 }
1526 }
1527
1528 poly_normalize(out);
1529 }
1530
1531 static void poly_from_poly3(struct poly *out, const struct poly3 *in) {
1532 const crypto_word_t *words_s = in->s.v;
1533 const crypto_word_t *words_a = in->a.v;
1534 crypto_word_t word_s = ~(*words_s);
1535 crypto_word_t word_a = *words_a;
1536 unsigned shift = 0;
1537
1538 for (unsigned i = 0; i < N; i++) {
1539 out->v[i] = (uint16_t)(word_s & 1) - 1;
1540 out->v[i] |= word_a & 1;
1541 word_s >>= 1;
1542 word_a >>= 1;
1543 shift++;
1544
1545 if (shift == BITS_PER_WORD) {
1546 words_s++;
1547 words_a++;
1548 word_s = ~(*words_s);
1549 word_a = *words_a;
1550 shift = 0;
1551 }
1552 }
1553
1554 poly_normalize(out);
1555 }
1556
1557 // Polynomial inversion
1558 // --------------------
1559
1560 // poly_invert_mod2 sets |*out| to |in^-1| (i.e. such that |*out|×|in| = 1 mod
1561 // Φ(N)), all mod 2. This isn't useful in itself, but is part of doing inversion
1562 // mod Q.
1563 static void poly_invert_mod2(struct poly *out, const struct poly *in) {
1564 // This algorithm is taken from section 7.1 of [SAFEGCD].
1565 struct poly2 v, r, f, g;
1566
1567 // v = 0
1568 poly2_zero(&v);
1569 // r = 1
1570 poly2_zero(&r);
1571 r.v[0] = 1;
1572 // f = all ones.
1573 OPENSSL_memset(&f, 0xff, sizeof(struct poly2));
1574 f.v[WORDS_PER_POLY - 1] >>= BITS_PER_WORD - BITS_IN_LAST_WORD;
1575 // g is the reversal of |in|.
1576 poly2_from_poly(&g, in);
1577 poly2_mod_phiN(&g);
1578 poly2_reverse_700(&g, &g);
1579 int delta = 1;
1580
1581 for (size_t i = 0; i < (2*(N-1)) - 1; i++) {
1582 poly2_lshift1(&v);
1583
1584 const crypto_word_t delta_sign_bit = (delta >> (sizeof(delta) * 8 - 1)) & 1;
1585 const crypto_word_t delta_is_non_negative = delta_sign_bit - 1;
1586 const crypto_word_t delta_is_non_zero = ~constant_time_is_zero_w(delta);
1587 const crypto_word_t g_has_constant_term = lsb_to_all(g.v[0]);
1588 const crypto_word_t mask =
1589 g_has_constant_term & delta_is_non_negative & delta_is_non_zero;
1590
1591 const crypto_word_t c = lsb_to_all(f.v[0] & g.v[0]);
1592
1593 delta = constant_time_select_int(mask, -delta, delta);
1594 delta++;
1595
1596 poly2_cswap(&f, &g, mask);
1597 poly2_fmadd(&g, &f, c);
1598 poly2_rshift1(&g);
1599
1600 poly2_cswap(&v, &r, mask);
1601 poly2_fmadd(&r, &v, c);
1602 }
1603
1604 assert(delta == 0);
1605 assert(f.v[0] & 1);
1606 poly2_reverse_700(&v, &v);
1607 poly_from_poly2(out, &v);
1608 poly_assert_normalized(out);
1609 }
1610
1611 // poly_invert sets |*out| to |in^-1| (i.e. such that |*out|×|in| = 1 mod Φ(N)).
1612 static void poly_invert(struct POLY_MUL_SCRATCH *scratch, struct poly *out,
1613 const struct poly *in) {
1614 // Inversion mod Q, which is done based on the result of inverting mod
1615 // 2. See [NTRUTN14] paper, bottom of page two.
1616 struct poly a, *b, tmp;
1617
1618 // a = -in.
1619 for (unsigned i = 0; i < N; i++) {
1620 a.v[i] = -in->v[i];
1621 }
1622 poly_normalize(&a);
1623
1624 // b = in^-1 mod 2.
1625 b = out;
1626 poly_invert_mod2(b, in);
1627
1628 // We are working mod Q=2**13 and we need to iterate ceil(log_2(13))
1629 // times, which is four.
1630 for (unsigned i = 0; i < 4; i++) {
1631 poly_mul(scratch, &tmp, &a, b);
1632 tmp.v[0] += 2;
1633 poly_mul(scratch, b, b, &tmp);
1634 }
1635
1636 poly_assert_normalized(out);
1637 }
1638
1639 // Marshal and unmarshal functions for various basic types.
1640 // --------------------------------------------------------
1641
1642 #define POLY_BYTES 1138
1643
1644 // poly_marshal serialises all but the final coefficient of |in| to |out|.
1645 static void poly_marshal(uint8_t out[POLY_BYTES], const struct poly *in) {
1646 const uint16_t *p = in->v;
1647
1648 for (size_t i = 0; i < N / 8; i++) {
1649 out[0] = p[0];
1650 out[1] = (0x1f & (p[0] >> 8)) | ((p[1] & 0x07) << 5);
1651 out[2] = p[1] >> 3;
1652 out[3] = (3 & (p[1] >> 11)) | ((p[2] & 0x3f) << 2);
1653 out[4] = (0x7f & (p[2] >> 6)) | ((p[3] & 0x01) << 7);
1654 out[5] = p[3] >> 1;
1655 out[6] = (0xf & (p[3] >> 9)) | ((p[4] & 0x0f) << 4);
1656 out[7] = p[4] >> 4;
1657 out[8] = (1 & (p[4] >> 12)) | ((p[5] & 0x7f) << 1);
1658 out[9] = (0x3f & (p[5] >> 7)) | ((p[6] & 0x03) << 6);
1659 out[10] = p[6] >> 2;
1660 out[11] = (7 & (p[6] >> 10)) | ((p[7] & 0x1f) << 3);
1661 out[12] = p[7] >> 5;
1662
1663 p += 8;
1664 out += 13;
1665 }
1666
1667 // There are four remaining values.
1668 out[0] = p[0];
1669 out[1] = (0x1f & (p[0] >> 8)) | ((p[1] & 0x07) << 5);
1670 out[2] = p[1] >> 3;
1671 out[3] = (3 & (p[1] >> 11)) | ((p[2] & 0x3f) << 2);
1672 out[4] = (0x7f & (p[2] >> 6)) | ((p[3] & 0x01) << 7);
1673 out[5] = p[3] >> 1;
1674 out[6] = 0xf & (p[3] >> 9);
1675 }
1676
1677 // poly_unmarshal parses the output of |poly_marshal| and sets |out| such that
1678 // all but the final coefficients match, and the final coefficient is calculated
1679 // such that evaluating |out| at one results in zero. It returns one on success
1680 // or zero if |in| is an invalid encoding.
1681 static int poly_unmarshal(struct poly *out, const uint8_t in[POLY_BYTES]) {
1682 uint16_t *p = out->v;
1683
1684 for (size_t i = 0; i < N / 8; i++) {
1685 p[0] = (uint16_t)(in[0]) | (uint16_t)(in[1] & 0x1f) << 8;
1686 p[1] = (uint16_t)(in[1] >> 5) | (uint16_t)(in[2]) << 3 |
1687 (uint16_t)(in[3] & 3) << 11;
1688 p[2] = (uint16_t)(in[3] >> 2) | (uint16_t)(in[4] & 0x7f) << 6;
1689 p[3] = (uint16_t)(in[4] >> 7) | (uint16_t)(in[5]) << 1 |
1690 (uint16_t)(in[6] & 0xf) << 9;
1691 p[4] = (uint16_t)(in[6] >> 4) | (uint16_t)(in[7]) << 4 |
1692 (uint16_t)(in[8] & 1) << 12;
1693 p[5] = (uint16_t)(in[8] >> 1) | (uint16_t)(in[9] & 0x3f) << 7;
1694 p[6] = (uint16_t)(in[9] >> 6) | (uint16_t)(in[10]) << 2 |
1695 (uint16_t)(in[11] & 7) << 10;
1696 p[7] = (uint16_t)(in[11] >> 3) | (uint16_t)(in[12]) << 5;
1697
1698 p += 8;
1699 in += 13;
1700 }
1701
1702 // There are four coefficients remaining.
1703 p[0] = (uint16_t)(in[0]) | (uint16_t)(in[1] & 0x1f) << 8;
1704 p[1] = (uint16_t)(in[1] >> 5) | (uint16_t)(in[2]) << 3 |
1705 (uint16_t)(in[3] & 3) << 11;
1706 p[2] = (uint16_t)(in[3] >> 2) | (uint16_t)(in[4] & 0x7f) << 6;
1707 p[3] = (uint16_t)(in[4] >> 7) | (uint16_t)(in[5]) << 1 |
1708 (uint16_t)(in[6] & 0xf) << 9;
1709
1710 for (unsigned i = 0; i < N - 1; i++) {
1711 out->v[i] = (int16_t)(out->v[i] << 3) >> 3;
1712 }
1713
1714 // There are four unused bits in the last byte. We require them to be zero.
1715 if ((in[6] & 0xf0) != 0) {
1716 return 0;
1717 }
1718
1719 // Set the final coefficient as specifed in [HRSSNIST] 1.9.2 step 6.
1720 uint32_t sum = 0;
1721 for (size_t i = 0; i < N - 1; i++) {
1722 sum += out->v[i];
1723 }
1724
1725 out->v[N - 1] = (uint16_t)(0u - sum);
1726 poly_normalize(out);
1727
1728 return 1;
1729 }
1730
1731 // mod3_from_modQ maps {0, 1, Q-1, 65535} -> {0, 1, 2, 2}. Note that |v| may
1732 // have an invalid value when processing attacker-controlled inputs.
1733 static uint16_t mod3_from_modQ(uint16_t v) {
1734 v &= 3;
1735 return v ^ (v >> 1);
1736 }
1737
1738 // poly_marshal_mod3 marshals |in| to |out| where the coefficients of |in| are
1739 // all in {0, 1, Q-1, 65535} and |in| is mod Φ(N). (Note that coefficients may
1740 // have invalid values when processing attacker-controlled inputs.)
1741 static void poly_marshal_mod3(uint8_t out[HRSS_POLY3_BYTES],
1742 const struct poly *in) {
1743 const uint16_t *coeffs = in->v;
1744
1745 // Only 700 coefficients are marshaled because in[700] must be zero.
1746 assert(coeffs[N-1] == 0);
1747
1748 for (size_t i = 0; i < HRSS_POLY3_BYTES; i++) {
1749 const uint16_t coeffs0 = mod3_from_modQ(coeffs[0]);
1750 const uint16_t coeffs1 = mod3_from_modQ(coeffs[1]);
1751 const uint16_t coeffs2 = mod3_from_modQ(coeffs[2]);
1752 const uint16_t coeffs3 = mod3_from_modQ(coeffs[3]);
1753 const uint16_t coeffs4 = mod3_from_modQ(coeffs[4]);
1754 out[i] = coeffs0 + coeffs1 * 3 + coeffs2 * 9 + coeffs3 * 27 + coeffs4 * 81;
1755 coeffs += 5;
1756 }
1757 }
1758
1759 // HRSS-specific functions
1760 // -----------------------
1761
1762 // poly_short_sample samples a vector of values in {0xffff (i.e. -1), 0, 1}.
1763 // This is the same action as the algorithm in [HRSSNIST] section 1.8.1, but
1764 // with HRSS-SXY the sampling algorithm is now a private detail of the
1765 // implementation (previously it had to match between two parties). This
1766 // function uses that freedom to implement a flatter distribution of values.
1767 static void poly_short_sample(struct poly *out,
1768 const uint8_t in[HRSS_SAMPLE_BYTES]) {
1769 OPENSSL_STATIC_ASSERT(HRSS_SAMPLE_BYTES == N - 1,
1770 HRSS_SAMPLE_BYTES_incorrect)
1771 for (size_t i = 0; i < N - 1; i++) {
1772 uint16_t v = mod3(in[i]);
1773 // Map {0, 1, 2} -> {0, 1, 0xffff}
1774 v |= ((v >> 1) ^ 1) - 1;
1775 out->v[i] = v;
1776 }
1777 out->v[N - 1] = 0;
1778 poly_normalize(out);
1779 }
1780
1781 // poly_short_sample_plus performs the T+ sample as defined in [HRSSNIST],
1782 // section 1.8.2.
1783 static void poly_short_sample_plus(struct poly *out,
1784 const uint8_t in[HRSS_SAMPLE_BYTES]) {
1785 poly_short_sample(out, in);
1786
1787 // sum (and the product in the for loop) will overflow. But that's fine
1788 // because |sum| is bound by +/- (N-2), and N < 2^15 so it works out.
1789 uint16_t sum = 0;
1790 for (unsigned i = 0; i < N - 2; i++) {
1791 sum += (unsigned) out->v[i] * out->v[i + 1];
1792 }
1793
1794 // If the sum is negative, flip the sign of even-positioned coefficients. (See
1795 // page 8 of [HRSS].)
1796 sum = ((int16_t) sum) >> 15;
1797 const uint16_t scale = sum | (~sum & 1);
1798 for (unsigned i = 0; i < N; i += 2) {
1799 out->v[i] = (unsigned) out->v[i] * scale;
1800 }
1801 poly_assert_normalized(out);
1802 }
1803
1804 // poly_lift computes the function discussed in [HRSS], appendix B.
1805 static void poly_lift(struct poly *out, const struct poly *a) {
1806 // We wish to calculate a/(𝑥-1) mod Φ(N) over GF(3), where Φ(N) is the
1807 // Nth cyclotomic polynomial, i.e. 1 + 𝑥 + … + 𝑥^700 (since N is prime).
1808
1809 // 1/(𝑥-1) has a fairly basic structure that we can exploit to speed this up:
1810 //
1811 // R.<x> = PolynomialRing(GF(3)…)
1812 // inv = R.cyclotomic_polynomial(1).inverse_mod(R.cyclotomic_polynomial(n))
1813 // list(inv)[:15]
1814 // [1, 0, 2, 1, 0, 2, 1, 0, 2, 1, 0, 2, 1, 0, 2]
1815 //
1816 // This three-element pattern of coefficients repeats for the whole
1817 // polynomial.
1818 //
1819 // Next define the overbar operator such that z̅ = z[0] +
1820 // reverse(z[1:]). (Index zero of a polynomial here is the coefficient
1821 // of the constant term. So index one is the coefficient of 𝑥 and so
1822 // on.)
1823 //
1824 // A less odd way to define this is to see that z̅ negates the indexes,
1825 // so z̅[0] = z[-0], z̅[1] = z[-1] and so on.
1826 //
1827 // The use of z̅ is that, when working mod (𝑥^701 - 1), vz[0] = <v,
1828 // z̅>, vz[1] = <v, 𝑥z̅>, …. (Where <a, b> is the inner product: the sum
1829 // of the point-wise products.) Although we calculated the inverse mod
1830 // Φ(N), we can work mod (𝑥^N - 1) and reduce mod Φ(N) at the end.
1831 // (That's because (𝑥^N - 1) is a multiple of Φ(N).)
1832 //
1833 // When working mod (𝑥^N - 1), multiplication by 𝑥 is a right-rotation
1834 // of the list of coefficients.
1835 //
1836 // Thus we can consider what the pattern of z̅, 𝑥z̅, 𝑥^2z̅, … looks like:
1837 //
1838 // def reverse(xs):
1839 // suffix = list(xs[1:])
1840 // suffix.reverse()
1841 // return [xs[0]] + suffix
1842 //
1843 // def rotate(xs):
1844 // return [xs[-1]] + xs[:-1]
1845 //
1846 // zoverbar = reverse(list(inv) + [0])
1847 // xzoverbar = rotate(reverse(list(inv) + [0]))
1848 // x2zoverbar = rotate(rotate(reverse(list(inv) + [0])))
1849 //
1850 // zoverbar[:15]
1851 // [1, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1]
1852 // xzoverbar[:15]
1853 // [0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0]
1854 // x2zoverbar[:15]
1855 // [2, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
1856 //
1857 // (For a formula for z̅, see lemma two of appendix B.)
1858 //
1859 // After the first three elements have been taken care of, all then have
1860 // a repeating three-element cycle. The next value (𝑥^3z̅) involves
1861 // three rotations of the first pattern, thus the three-element cycle
1862 // lines up. However, the discontinuity in the first three elements
1863 // obviously moves to a different position. Consider the difference
1864 // between 𝑥^3z̅ and z̅:
1865 //
1866 // [x-y for (x,y) in zip(zoverbar, x3zoverbar)][:15]
1867 // [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1868 //
1869 // This pattern of differences is the same for all elements, although it
1870 // obviously moves right with the rotations.
1871 //
1872 // From this, we reach algorithm eight of appendix B.
1873
1874 // Handle the first three elements of the inner products.
1875 out->v[0] = a->v[0] + a->v[2];
1876 out->v[1] = a->v[1];
1877 out->v[2] = -a->v[0] + a->v[2];
1878
1879 // s0, s1, s2 are added into out->v[0], out->v[1], and out->v[2],
1880 // respectively. We do not compute s1 because it's just -(s0 + s1).
1881 uint16_t s0 = 0, s2 = 0;
1882 for (size_t i = 3; i < 699; i += 3) {
1883 s0 += -a->v[i] + a->v[i + 2];
1884 // s1 += a->v[i] - a->v[i + 1];
1885 s2 += a->v[i + 1] - a->v[i + 2];
1886 }
1887
1888 // Handle the fact that the three-element pattern doesn't fill the
1889 // polynomial exactly (since 701 isn't a multiple of three).
1890 s0 -= a->v[699];
1891 // s1 += a->v[699] - a->v[700];
1892 s2 += a->v[700];
1893
1894 // Note that s0 + s1 + s2 = 0.
1895 out->v[0] += s0;
1896 out->v[1] -= (s0 + s2); // = s1
1897 out->v[2] += s2;
1898
1899 // Calculate the remaining inner products by taking advantage of the
1900 // fact that the pattern repeats every three cycles and the pattern of
1901 // differences moves with the rotation.
1902 for (size_t i = 3; i < N; i++) {
1903 out->v[i] = (out->v[i - 3] - (a->v[i - 2] + a->v[i - 1] + a->v[i]));
1904 }
1905
1906 // Reduce mod Φ(N) by subtracting a multiple of out[700] from every
1907 // element and convert to mod Q. (See above about adding twice as
1908 // subtraction.)
1909 const crypto_word_t v = out->v[700];
1910 for (unsigned i = 0; i < N; i++) {
1911 const uint16_t vi_mod3 = mod3(out->v[i] - v);
1912 // Map {0, 1, 2} to {0, 1, 0xffff}.
1913 out->v[i] = (~((vi_mod3 >> 1) - 1)) | vi_mod3;
1914 }
1915
1916 poly_mul_x_minus_1(out);
1917 poly_normalize(out);
1918 }
1919
1920 struct public_key {
1921 struct poly ph;
1922 };
1923
1924 struct private_key {
1925 struct poly3 f, f_inverse;
1926 struct poly ph_inverse;
1927 uint8_t hmac_key[32];
1928 };
1929
1930 // public_key_from_external converts an external public key pointer into an
1931 // internal one. Externally the alignment is only specified to be eight bytes
1932 // but we need 16-byte alignment. We could annotate the external struct with
1933 // that alignment but we can only assume that malloced pointers are 8-byte
1934 // aligned in any case. (Even if the underlying malloc returns values with
1935 // 16-byte alignment, |OPENSSL_malloc| will store an 8-byte size prefix and mess
1936 // that up.)
1937 static struct public_key *public_key_from_external(
1938 struct HRSS_public_key *ext) {
1939 OPENSSL_STATIC_ASSERT(
1940 sizeof(struct HRSS_public_key) >= sizeof(struct public_key) + 15,
1941 HRSS_public_key_too_small)
1942
1943 return align_pointer(ext->opaque, 16);
1944 }
1945
1946 // private_key_from_external does the same thing as |public_key_from_external|,
1947 // but for private keys. See the comment on that function about alignment
1948 // issues.
1949 static struct private_key *private_key_from_external(
1950 struct HRSS_private_key *ext) {
1951 OPENSSL_STATIC_ASSERT(
1952 sizeof(struct HRSS_private_key) >= sizeof(struct private_key) + 15,
1953 HRSS_private_key_too_small)
1954
1955 return align_pointer(ext->opaque, 16);
1956 }
1957
1958 // malloc_align32 returns a pointer to |size| bytes of 32-byte-aligned heap and
1959 // sets |*out_ptr| to a value that can be passed to |OPENSSL_free| to release
1960 // it. It returns NULL if out of memory.
1961 static void *malloc_align32(void **out_ptr, size_t size) {
1962 void *ptr = OPENSSL_malloc(size + 31);
1963 if (!ptr) {
1964 *out_ptr = NULL;
1965 return NULL;
1966 }
1967
1968 *out_ptr = ptr;
1969 return align_pointer(ptr, 32);
1970 }
1971
1972 int HRSS_generate_key(
1973 struct HRSS_public_key *out_pub, struct HRSS_private_key *out_priv,
1974 const uint8_t in[HRSS_SAMPLE_BYTES + HRSS_SAMPLE_BYTES + 32]) {
1975 struct public_key *pub = public_key_from_external(out_pub);
1976 struct private_key *priv = private_key_from_external(out_priv);
1977
1978 struct vars {
1979 struct POLY_MUL_SCRATCH scratch;
1980 struct poly f;
1981 struct poly pg_phi1;
1982 struct poly pfg_phi1;
1983 struct poly pfg_phi1_inverse;
1984 };
1985
1986 void *malloc_ptr;
1987 struct vars *const vars = malloc_align32(&malloc_ptr, sizeof(struct vars));
1988 if (!vars) {
1989 // If the caller ignores the return value the output will still be safe.
1990 // The private key output is randomised in case it's later passed to
1991 // |HRSS_encap|.
1992 memset(out_pub, 0, sizeof(struct HRSS_public_key));
1993 AWSLC_ABORT_IF_NOT_ONE(RAND_bytes((uint8_t*) out_priv, sizeof(struct HRSS_private_key)));
1994 return 0;
1995 }
1996
1997 #if !defined(NDEBUG)
1998 OPENSSL_memset(vars, 0xff, sizeof(struct vars));
1999 #endif
2000
2001 OPENSSL_memcpy(priv->hmac_key, in + 2 * HRSS_SAMPLE_BYTES,
2002 sizeof(priv->hmac_key));
2003
2004 poly_short_sample_plus(&vars->f, in);
2005 poly3_from_poly(&priv->f, &vars->f);
2006 HRSS_poly3_invert(&priv->f_inverse, &priv->f);
2007
2008 // pg_phi1 is p (i.e. 3) × g × Φ(1) (i.e. 𝑥-1).
2009 poly_short_sample_plus(&vars->pg_phi1, in + HRSS_SAMPLE_BYTES);
2010 for (unsigned i = 0; i < N; i++) {
2011 vars->pg_phi1.v[i] *= 3;
2012 }
2013 poly_mul_x_minus_1(&vars->pg_phi1);
2014
2015 poly_mul(&vars->scratch, &vars->pfg_phi1, &vars->f, &vars->pg_phi1);
2016
2017 poly_invert(&vars->scratch, &vars->pfg_phi1_inverse, &vars->pfg_phi1);
2018
2019 poly_mul(&vars->scratch, &pub->ph, &vars->pfg_phi1_inverse, &vars->pg_phi1);
2020 poly_mul(&vars->scratch, &pub->ph, &pub->ph, &vars->pg_phi1);
2021 poly_clamp(&pub->ph);
2022
2023 poly_mul(&vars->scratch, &priv->ph_inverse, &vars->pfg_phi1_inverse,
2024 &vars->f);
2025 poly_mul(&vars->scratch, &priv->ph_inverse, &priv->ph_inverse, &vars->f);
2026 poly_clamp(&priv->ph_inverse);
2027
2028 OPENSSL_free(malloc_ptr);
2029 return 1;
2030 }
2031
2032 static const char kSharedKey[] = "shared key";
2033
2034 int HRSS_encap(uint8_t out_ciphertext[POLY_BYTES], uint8_t out_shared_key[32],
2035 const struct HRSS_public_key *in_pub,
2036 const uint8_t in[HRSS_SAMPLE_BYTES + HRSS_SAMPLE_BYTES]) {
2037 const struct public_key *pub =
2038 public_key_from_external((struct HRSS_public_key *)in_pub);
2039
2040 struct vars {
2041 struct POLY_MUL_SCRATCH scratch;
2042 struct poly m, r, m_lifted;
2043 struct poly prh_plus_m;
2044 SHA256_CTX hash_ctx;
2045 uint8_t m_bytes[HRSS_POLY3_BYTES];
2046 uint8_t r_bytes[HRSS_POLY3_BYTES];
2047 };
2048
2049 void *malloc_ptr;
2050 struct vars *const vars = malloc_align32(&malloc_ptr, sizeof(struct vars));
2051 if (!vars) {
2052 // If the caller ignores the return value the output will still be safe.
2053 // The private key output is randomised in case it's used to encrypt and
2054 // transmit something.
2055 memset(out_ciphertext, 0, POLY_BYTES);
2056 AWSLC_ABORT_IF_NOT_ONE(RAND_bytes(out_shared_key, 32));
2057 return 0;
2058 }
2059
2060 #if !defined(NDEBUG)
2061 OPENSSL_memset(vars, 0xff, sizeof(struct vars));
2062 #endif
2063
2064 poly_short_sample(&vars->m, in);
2065 poly_short_sample(&vars->r, in + HRSS_SAMPLE_BYTES);
2066 poly_lift(&vars->m_lifted, &vars->m);
2067
2068 poly_mul(&vars->scratch, &vars->prh_plus_m, &vars->r, &pub->ph);
2069 for (unsigned i = 0; i < N; i++) {
2070 vars->prh_plus_m.v[i] += vars->m_lifted.v[i];
2071 }
2072
2073 poly_marshal(out_ciphertext, &vars->prh_plus_m);
2074
2075 poly_marshal_mod3(vars->m_bytes, &vars->m);
2076 poly_marshal_mod3(vars->r_bytes, &vars->r);
2077
2078 SHA256_Init(&vars->hash_ctx);
2079 SHA256_Update(&vars->hash_ctx, kSharedKey, sizeof(kSharedKey));
2080 SHA256_Update(&vars->hash_ctx, vars->m_bytes, sizeof(vars->m_bytes));
2081 SHA256_Update(&vars->hash_ctx, vars->r_bytes, sizeof(vars->r_bytes));
2082 SHA256_Update(&vars->hash_ctx, out_ciphertext, POLY_BYTES);
2083 SHA256_Final(out_shared_key, &vars->hash_ctx);
2084
2085 OPENSSL_free(malloc_ptr);
2086 return 1;
2087 }
2088
2089 int HRSS_decap(uint8_t out_shared_key[HRSS_KEY_BYTES],
2090 const struct HRSS_private_key *in_priv,
2091 const uint8_t *ciphertext, size_t ciphertext_len) {
2092 const struct private_key *priv =
2093 private_key_from_external((struct HRSS_private_key *)in_priv);
2094
2095 struct vars {
2096 struct POLY_MUL_SCRATCH scratch;
2097 uint8_t masked_key[SHA256_CBLOCK];
2098 SHA256_CTX hash_ctx;
2099 struct poly c;
2100 struct poly f, cf;
2101 struct poly3 cf3, m3;
2102 struct poly m, m_lifted;
2103 struct poly r;
2104 struct poly3 r3;
2105 uint8_t expected_ciphertext[HRSS_CIPHERTEXT_BYTES];
2106 uint8_t m_bytes[HRSS_POLY3_BYTES];
2107 uint8_t r_bytes[HRSS_POLY3_BYTES];
2108 uint8_t shared_key[32];
2109 };
2110
2111 void *malloc_ptr;
2112 struct vars *const vars = malloc_align32(&malloc_ptr, sizeof(struct vars));
2113 if (!vars) {
2114 // If the caller ignores the return value the output will still be safe.
2115 // The private key output is randomised in case it's used to encrypt and
2116 // transmit something.
2117 AWSLC_ABORT_IF_NOT_ONE(RAND_bytes(out_shared_key, HRSS_KEY_BYTES));
2118 return 0;
2119 }
2120
2121 #if !defined(NDEBUG)
2122 OPENSSL_memset(vars, 0xff, sizeof(struct vars));
2123 #endif
2124
2125 // This is HMAC, expanded inline rather than using the |HMAC| function so that
2126 // we can avoid dealing with possible allocation failures and so keep this
2127 // function infallible.
2128 OPENSSL_STATIC_ASSERT(sizeof(priv->hmac_key) <= sizeof(vars->masked_key),
2129 HRSS_HMAC_key_larger_than_SHA_256_block_size)
2130
2131 for (size_t i = 0; i < sizeof(priv->hmac_key); i++) {
2132 vars->masked_key[i] = priv->hmac_key[i] ^ 0x36;
2133 }
2134 OPENSSL_memset(vars->masked_key + sizeof(priv->hmac_key), 0x36,
2135 sizeof(vars->masked_key) - sizeof(priv->hmac_key));
2136
2137 SHA256_Init(&vars->hash_ctx);
2138 SHA256_Update(&vars->hash_ctx, vars->masked_key, sizeof(vars->masked_key));
2139 SHA256_Update(&vars->hash_ctx, ciphertext, ciphertext_len);
2140 uint8_t inner_digest[SHA256_DIGEST_LENGTH];
2141 SHA256_Final(inner_digest, &vars->hash_ctx);
2142
2143 for (size_t i = 0; i < sizeof(priv->hmac_key); i++) {
2144 vars->masked_key[i] ^= (0x5c ^ 0x36);
2145 }
2146 OPENSSL_memset(vars->masked_key + sizeof(priv->hmac_key), 0x5c,
2147 sizeof(vars->masked_key) - sizeof(priv->hmac_key));
2148
2149 SHA256_Init(&vars->hash_ctx);
2150 SHA256_Update(&vars->hash_ctx, vars->masked_key, sizeof(vars->masked_key));
2151 SHA256_Update(&vars->hash_ctx, inner_digest, sizeof(inner_digest));
2152 OPENSSL_STATIC_ASSERT(HRSS_KEY_BYTES == SHA256_DIGEST_LENGTH,
2153 HRSS_shared_key_length_incorrect)
2154 SHA256_Final(out_shared_key, &vars->hash_ctx);
2155
2156 // If the ciphertext is publicly invalid then a random shared key is still
2157 // returned to simply the logic of the caller, but this path is not constant
2158 // time.
2159 if (ciphertext_len != HRSS_CIPHERTEXT_BYTES ||
2160 !poly_unmarshal(&vars->c, ciphertext)) {
2161 goto out;
2162 }
2163
2164 poly_from_poly3(&vars->f, &priv->f);
2165 poly_mul(&vars->scratch, &vars->cf, &vars->c, &vars->f);
2166 poly3_from_poly(&vars->cf3, &vars->cf);
2167 // Note that cf3 is not reduced mod Φ(N). That reduction is deferred.
2168 HRSS_poly3_mul(&vars->m3, &vars->cf3, &priv->f_inverse);
2169
2170 poly_from_poly3(&vars->m, &vars->m3);
2171 poly_lift(&vars->m_lifted, &vars->m);
2172
2173 for (unsigned i = 0; i < N; i++) {
2174 vars->r.v[i] = vars->c.v[i] - vars->m_lifted.v[i];
2175 }
2176 poly_normalize(&vars->r);
2177 poly_mul(&vars->scratch, &vars->r, &vars->r, &priv->ph_inverse);
2178 poly_mod_phiN(&vars->r);
2179 poly_clamp(&vars->r);
2180
2181 crypto_word_t ok = poly3_from_poly_checked(&vars->r3, &vars->r);
2182
2183 // [NTRUCOMP] section 5.1 includes ReEnc2 and a proof that it's valid. Rather
2184 // than do an expensive |poly_mul|, it rebuilds |c'| from |c - lift(m)|
2185 // (called |b|) with:
2186 // t = (−b(1)/N) mod Q
2187 // c' = b + tΦ(N) + lift(m) mod Q
2188 //
2189 // When polynomials are transmitted, the final coefficient is omitted and
2190 // |poly_unmarshal| sets it such that f(1) == 0. Thus c(1) == 0. Also,
2191 // |poly_lift| multiplies the result by (x-1) and therefore evaluating a
2192 // lifted polynomial at 1 is also zero. Thus lift(m)(1) == 0 and so
2193 // (c - lift(m))(1) == 0.
2194 //
2195 // Although we defer the reduction above, |b| is conceptually reduced mod
2196 // Φ(N). In order to do that reduction one subtracts |c[N-1]| from every
2197 // coefficient. Therefore b(1) = -c[N-1]×N. The value of |t|, above, then is
2198 // just recovering |c[N-1]|, and adding tΦ(N) is simply undoing the reduction.
2199 // Therefore b + tΦ(N) + lift(m) = c by construction and we don't need to
2200 // recover |c| at all so long as we do the checks in
2201 // |poly3_from_poly_checked|.
2202 //
2203 // The |poly_marshal| here then is just confirming that |poly_unmarshal| is
2204 // strict and could be omitted.
2205
2206 OPENSSL_STATIC_ASSERT(HRSS_CIPHERTEXT_BYTES == POLY_BYTES,
2207 ciphertext_is_the_wrong_size)
2208 assert(ciphertext_len == sizeof(vars->expected_ciphertext));
2209 poly_marshal(vars->expected_ciphertext, &vars->c);
2210
2211 poly_marshal_mod3(vars->m_bytes, &vars->m);
2212 poly_marshal_mod3(vars->r_bytes, &vars->r);
2213
2214 ok &= constant_time_is_zero_w(
2215 CRYPTO_memcmp(ciphertext, vars->expected_ciphertext,
2216 sizeof(vars->expected_ciphertext)));
2217
2218 SHA256_Init(&vars->hash_ctx);
2219 SHA256_Update(&vars->hash_ctx, kSharedKey, sizeof(kSharedKey));
2220 SHA256_Update(&vars->hash_ctx, vars->m_bytes, sizeof(vars->m_bytes));
2221 SHA256_Update(&vars->hash_ctx, vars->r_bytes, sizeof(vars->r_bytes));
2222 SHA256_Update(&vars->hash_ctx, vars->expected_ciphertext,
2223 sizeof(vars->expected_ciphertext));
2224 SHA256_Final(vars->shared_key, &vars->hash_ctx);
2225
2226 for (unsigned i = 0; i < sizeof(vars->shared_key); i++) {
2227 out_shared_key[i] =
2228 constant_time_select_8(ok, vars->shared_key[i], out_shared_key[i]);
2229 }
2230
2231 out:
2232 OPENSSL_free(malloc_ptr);
2233 return 1;
2234 }
2235
2236 void HRSS_marshal_public_key(uint8_t out[HRSS_PUBLIC_KEY_BYTES],
2237 const struct HRSS_public_key *in_pub) {
2238 const struct public_key *pub =
2239 public_key_from_external((struct HRSS_public_key *)in_pub);
2240 poly_marshal(out, &pub->ph);
2241 }
2242
2243 int HRSS_parse_public_key(struct HRSS_public_key *out,
2244 const uint8_t in[HRSS_PUBLIC_KEY_BYTES]) {
2245 struct public_key *pub = public_key_from_external(out);
2246 if (!poly_unmarshal(&pub->ph, in)) {
2247 return 0;
2248 }
2249 OPENSSL_memset(&pub->ph.v[N], 0, 3 * sizeof(uint16_t));
2250 return 1;
2251 }