From f56dd68c1c325ee54c942d783b33826d85193794 Mon Sep 17 00:00:00 2001 From: Russell O'Connor Date: Thu, 11 Jan 2024 13:42:00 -0500 Subject: [PATCH] Avoid using out-of-bounds field elements (in impossible cases) secp256k1_fe_set_b32_limit says that when it returns 0, one is not allowed to use the resulting output value. This refactors the code so that the existing value of t is maintained in cases where sha256 would output an out-of-bounds hash value. Note: This situation is cryptographically impossible to occur. --- src/modules/generator/main_impl.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/modules/generator/main_impl.h b/src/modules/generator/main_impl.h index a00b22f42..135e8aa44 100644 --- a/src/modules/generator/main_impl.h +++ b/src/modules/generator/main_impl.h @@ -187,6 +187,7 @@ static int secp256k1_generator_generate_internal(const secp256k1_context* ctx, s static const unsigned char prefix1[17] = "1st generation: "; static const unsigned char prefix2[17] = "2nd generation: "; secp256k1_fe t = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 4); + secp256k1_fe set = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 0); secp256k1_ge add; secp256k1_gej accum; int overflow; @@ -205,7 +206,8 @@ static int secp256k1_generator_generate_internal(const secp256k1_context* ctx, s secp256k1_sha256_write(&sha256, prefix1, 16); secp256k1_sha256_write(&sha256, key32, 32); secp256k1_sha256_finalize(&sha256, b32); - ret &= secp256k1_fe_set_b32_limit(&t, b32); + ret &= secp256k1_fe_set_b32_limit(&set, b32); + secp256k1_fe_cmov(&t, &set, ret); shallue_van_de_woestijne(&add, &t); if (blind32) { secp256k1_gej_add_ge(&accum, &accum, &add); @@ -217,7 +219,8 @@ static int secp256k1_generator_generate_internal(const secp256k1_context* ctx, s secp256k1_sha256_write(&sha256, prefix2, 16); secp256k1_sha256_write(&sha256, key32, 32); secp256k1_sha256_finalize(&sha256, b32); - ret &= secp256k1_fe_set_b32_limit(&t, b32); + ret &= secp256k1_fe_set_b32_limit(&set, b32); + secp256k1_fe_cmov(&t, &set, ret); shallue_van_de_woestijne(&add, &t); secp256k1_gej_add_ge(&accum, &accum, &add);