Skip to content

Commit 5cfd895

Browse files
renemeFAlbertDevatreiber94
committed
FIX: potential non-constant time division
Some compilers generate a non-constant time division operation for the division by KyberConstants::Q. Fix is based on the patch in the reference implementation: pq-crystals/kyber@dda29cc Found and initially reported by Goutam Tamvada, Karthikeyan Bhargavan, and Franziskus Kiefer of @cryspen. Independently reported by djb as "Kyberslash". fixes #3844 Co-Authored-By: Fabian Albert <fabian.albert@rohde-schwarz.com> Co-Authored-By: Amos Treiber <amos.treiber@rohde-schwarz.com>
1 parent 3dbf4da commit 5cfd895

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

src/lib/pubkey/kyber/kyber_common/kyber.cpp

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -383,12 +383,21 @@ class Polynomial {
383383

384384
this->csubq();
385385

386+
auto compress = [](uint32_t t) {
387+
// (t << 1) + ((KyberConstants::Q / 2) / KyberConstants::Q) & 1
388+
// Note that magic numbers assume that ::Q = 3329
389+
t <<= 1;
390+
t += 1665;
391+
t *= 80635;
392+
t >>= 28;
393+
t &= 1;
394+
return static_cast<uint8_t>(t);
395+
};
396+
386397
for(size_t i = 0; i < size() / 8; ++i) {
387398
result[i] = 0;
388399
for(size_t j = 0; j < 8; ++j) {
389-
const uint16_t t = (((static_cast<uint16_t>(this->m_coeffs[8 * i + j]) << 1) + KyberConstants::Q / 2) /
390-
KyberConstants::Q);
391-
result[i] |= (t & 1) << j;
400+
result[i] |= compress(this->m_coeffs[8 * i + j]) << j;
392401
}
393402
}
394403

0 commit comments

Comments
 (0)