|
|
@@ -1,6 +1,7 @@ |
|
|
|
#include "params.h" |
|
|
|
#include "reduce.h" |
|
|
|
#include <stdint.h> |
|
|
|
#include <stdio.h> |
|
|
|
|
|
|
|
/************************************************* |
|
|
|
* Name: PQCLEAN_KYBER768_CLEAN_montgomery_reduce |
|
|
@@ -11,7 +12,7 @@ |
|
|
|
* Arguments: - int32_t a: input integer to be reduced; |
|
|
|
* has to be in {-q2^15,...,q2^15-1} |
|
|
|
* |
|
|
|
* Returns: integer in {-q+1,...,q-1} congruent to a * R^-1 modulo q. |
|
|
|
* Returns: integer in {-q+1,...,q-1} congruent to a * R^-1 modulo 2*q. |
|
|
|
**************************************************/ |
|
|
|
int16_t PQCLEAN_KYBER768_CLEAN_montgomery_reduce(int32_t a) { |
|
|
|
int32_t t; |
|
|
@@ -35,10 +36,34 @@ int16_t PQCLEAN_KYBER768_CLEAN_montgomery_reduce(int32_t a) { |
|
|
|
* Returns: integer in {-(q-1)/2,...,(q-1)/2} congruent to a modulo q. |
|
|
|
**************************************************/ |
|
|
|
int16_t PQCLEAN_KYBER768_CLEAN_barrett_reduce(int16_t a) { |
|
|
|
int16_t t; |
|
|
|
const int16_t v = ((1U << 26) + KYBER_Q / 2) / KYBER_Q; |
|
|
|
|
|
|
|
t = ((int32_t)v * a + (1 << 25)) >> 26; |
|
|
|
t *= KYBER_Q; |
|
|
|
return a - t; |
|
|
|
int32_t t; |
|
|
|
|
|
|
|
/* |
|
|
|
* Barrett reduction is applied to 16-bit signed |
|
|
|
* integers. We use q=26 to compute the reprociacal |
|
|
|
* floor(2^q / KYBER_Q), which is much larger than |
|
|
|
* any value of 'a'. That way, the final subtraction |
|
|
|
* can be avoided. (OZAPTF): perform bounds analysis |
|
|
|
* check if that's true). |
|
|
|
*/ |
|
|
|
#define KYBER_BARETT_q 26 |
|
|
|
/* |
|
|
|
* Reprocical used by Barrett reduction |
|
|
|
* floor(2^q / KYBER_Q) |
|
|
|
*/ |
|
|
|
#define KYBER_BARETT_U 20158 |
|
|
|
|
|
|
|
// Round the reprocical up |
|
|
|
t = (KYBER_BARETT_U+1)*a; |
|
|
|
// Add 1/2 * 2^25 to centrize |
|
|
|
// in {-(q-1)/2,...,(q-1)/2} mod KYBER_Q. |
|
|
|
t += 1<<25; |
|
|
|
// Last 4 bytes |
|
|
|
t >>= 26; |
|
|
|
// Final multiplication and subtraction |
|
|
|
return a - ((int16_t)t)*KYBER_Q; |
|
|
|
|
|
|
|
#undef KYBER_BARETT_q |
|
|
|
#undef KYBER_BARETT_U |
|
|
|
} |