From 0f97c2da34c1e30bfaf8025458953df5c39746d6 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Mon, 18 Aug 2025 07:22:28 -0700 Subject: [PATCH] Fix constant time conditional multiplication. Ternary operators still create branching scenarios, and the CPU may use branch prediction to speed up processing which creates a variable-time possibility. --- src/lib/crypto/nano-nacl.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/lib/crypto/nano-nacl.ts b/src/lib/crypto/nano-nacl.ts index 9d6d1b9..f443678 100644 --- a/src/lib/crypto/nano-nacl.ts +++ b/src/lib/crypto/nano-nacl.ts @@ -375,7 +375,15 @@ export class NanoNaCl { this.Square(chk, r[0]) this.Multiply(chk, chk, den) - this.Multiply(this.neq25519(chk, num) ? r[0] : new Float64Array(16), r[0], this.I) + + // if neq is true, multiply r[0] by I, else multiply by 1 for a no-op + const neq = this.neq25519(chk, num) + const I = new Float64Array(this.I) + for (let i = 0; i < 16; i++) { + I[i] *= neq + } + I[0] += neq ^ 1 + this.Multiply(r[0], r[0], I) this.Square(chk, r[0]) this.Multiply(chk, chk, den) -- 2.47.3