hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

commit 6603f946fc2fd6158778dca4d97e86b0f467a3fc
parent f97ee5c7a5c091685bd2484745c83009292be48f
Author: Armin Preiml <apreiml@strohwolke.at>
Date:   Fri,  6 May 2022 15:13:20 +0200

crypto::curve25519: move clamping to separate fn

so that scalarmult may not copy the scalar input, which is the private
key in x25519.

Signed-off-by: Armin Preiml <apreiml@strohwolke.at>

Diffstat:
Mcrypto/curve25519/+test.ha | 5++++-
Mcrypto/curve25519/curve25519.ha | 12++++++++----
2 files changed, 12 insertions(+), 5 deletions(-)

diff --git a/crypto/curve25519/+test.ha b/crypto/curve25519/+test.ha @@ -90,6 +90,7 @@ use crypto::random; let out: [SCALARSZ]u8 = [0...]; for (let i = 0z; i < 200; i += 1) { + clamp(&x); x25519(&out, &x, &BASEPOINT); x[..] = out[..]; }; @@ -187,7 +188,9 @@ use crypto::random; for (let i = 0z; i < len(vectors); i += 1) { let got: [SCALARSZ]u8 = [0...]; - scalarmult(&got, &vectors[i].0, &vectors[i].1); + let scalar = vectors[i].0; + clamp(&scalar); + scalarmult(&got, &scalar, &vectors[i].1); if (!bytes::equal(got[..], vectors[i].2[..])) { fmt::errorfln("Case i={} failed", i)!; printvector("in", &vectors[i].0); diff --git a/crypto/curve25519/curve25519.ha b/crypto/curve25519/curve25519.ha @@ -38,15 +38,19 @@ export fn scalarmult_base( scalarmult(out, scalar, &BASEPOINT); }; +// Prepares the scalar to avoid particular attacks. See the "clamping" section +// in Kleppmann's paper. +export fn clamp(scalar: *[SCALARSZ]u8) void = { + scalar[0] &= 0xf8; + scalar[31] = (scalar[31] & 0x7f) | 0x40; +}; + // Set out to the product (scalar * point) export fn scalarmult( out: *[SCALARSZ]u8, scalar: const *[SCALARSZ]u8, point: const *[POINTSZ]u8 ) void = { - let clamped: [32]u8 = *scalar; - clamped[0] &= 0xf8; - clamped[31] = (clamped[31] & 0x7f) | 0x40; let x = unpack25519(point); let b: elem = *&x; let a: elem = [1, 0...]; @@ -57,7 +61,7 @@ export fn scalarmult( for (let i = 254i; i >= 0; i -= 1) { let iz = i : size; - let bit = ((clamped[iz >> 3] >> (iz & 7)) & 1) : i64; + let bit = ((scalar[iz >> 3] >> (iz & 7)) & 1) : i64; swap25519(&a, &b, bit); swap25519(&c, &d, bit); addfe(&e, &a, &c);