1
1
mirror of https://github.com/henrydcase/pqc.git synced 2024-11-26 17:31:38 +00:00
pqcrypto/crypto_sign/dilithium-iii/clean/reduce.c

75 lines
1.7 KiB
C
Raw Normal View History

2019-01-16 09:15:18 +00:00
#include "reduce.h"
#include "params.h"
#include <stdint.h>
/*************************************************
* Name: montgomery_reduce
*
* Description: For finite field element a with 0 <= a <= Q*2^32,
* compute r \equiv a*2^{-32} (mod Q) such that 0 <= r < 2*Q.
*
* Arguments: - uint64_t: finite field element a
*
* Returns r.
**************************************************/
uint32_t montgomery_reduce(uint64_t a) {
2019-01-16 10:02:32 +00:00
uint64_t t;
2019-01-16 09:15:18 +00:00
2019-01-16 10:02:32 +00:00
t = a * QINV;
t &= (1ULL << 32) - 1;
t *= Q;
t = a + t;
t >>= 32;
return t;
2019-01-16 09:15:18 +00:00
}
/*************************************************
* Name: reduce32
*
* Description: For finite field element a, compute r \equiv a (mod Q)
* such that 0 <= r < 2*Q.
*
* Arguments: - uint32_t: finite field element a
*
* Returns r.
**************************************************/
uint32_t reduce32(uint32_t a) {
2019-01-16 10:02:32 +00:00
uint32_t t;
2019-01-16 09:15:18 +00:00
2019-01-16 10:02:32 +00:00
t = a & 0x7FFFFF;
a >>= 23;
t += (a << 13) - a;
return t;
2019-01-16 09:15:18 +00:00
}
/*************************************************
* Name: csubq
*
* Description: Subtract Q if input coefficient is bigger than Q.
*
* Arguments: - uint32_t: finite field element a
*
* Returns r.
**************************************************/
uint32_t csubq(uint32_t a) {
2019-01-16 10:02:32 +00:00
a -= Q;
a += ((int32_t)a >> 31) & Q;
return a;
2019-01-16 09:15:18 +00:00
}
/*************************************************
* Name: freeze
*
* Description: For finite field element a, compute standard
* representative r = a mod Q.
*
* Arguments: - uint32_t: finite field element a
*
* Returns r.
**************************************************/
uint32_t freeze(uint32_t a) {
2019-01-16 10:02:32 +00:00
a = reduce32(a);
a = csubq(a);
return a;
2019-01-16 09:15:18 +00:00
}