kyber512r3_reduce.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <stdint.h>
  2. #include "kyber512r3_params.h"
  3. #include "kyber512r3_reduce.h"
  4. S2N_ENSURE_PORTABLE_OPTIMIZATIONS
  5. /*************************************************
  6. * Name: montgomery_reduce
  7. *
  8. * Description: Montgomery reduction; given a 32-bit integer a, computes
  9. * 16-bit integer congruent to a * R^-1 mod q,
  10. * where R=2^16
  11. *
  12. * Arguments: - int32_t a: input integer to be reduced;
  13. * has to be in {-q2^15,...,q2^15-1}
  14. *
  15. * Returns: integer in {-q+1,...,q-1} congruent to a * R^-1 modulo q.
  16. **************************************************/
  17. int16_t montgomery_reduce(int32_t a) {
  18. int32_t t;
  19. int16_t u;
  20. u = a * S2N_KYBER_512_R3_QINV;
  21. t = (int32_t)u * S2N_KYBER_512_R3_Q;
  22. t = a - t;
  23. t >>= 16;
  24. return t;
  25. }
  26. /*************************************************
  27. * Name: barrett_reduce
  28. *
  29. * Description: Barrett reduction; given a 16-bit integer a, computes
  30. * 16-bit integer congruent to a mod q in {0,...,q}
  31. *
  32. * Arguments: - int16_t a: input integer to be reduced
  33. *
  34. * Returns: integer in {0,...,q} congruent to a modulo q.
  35. **************************************************/
  36. int16_t barrett_reduce(int16_t a) {
  37. int16_t t;
  38. const int16_t v = ((1U << 26) + S2N_KYBER_512_R3_Q / 2) / S2N_KYBER_512_R3_Q;
  39. t = (int32_t)v * a >> 26;
  40. t *= S2N_KYBER_512_R3_Q;
  41. return a - t;
  42. }
  43. /*************************************************
  44. * Name: csubq
  45. *
  46. * Description: Conditionallly subtract q
  47. *
  48. * Arguments: - int16_t x: input integer
  49. *
  50. * Returns: a - q if a >= q, else a
  51. **************************************************/
  52. int16_t csubq(int16_t a) {
  53. a -= S2N_KYBER_512_R3_Q;
  54. a += (a >> 15) & S2N_KYBER_512_R3_Q;
  55. return a;
  56. }