Skip to content

Commit

Permalink
Verify the result of GMP modular inverse using non-GMP code
Browse files Browse the repository at this point in the history
  • Loading branch information
sipa committed Jul 9, 2015
1 parent 0cbc860 commit 36b305a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/field_impl.h
Expand Up @@ -212,6 +212,10 @@ static void secp256k1_fe_inv_var(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
secp256k1_fe_inv(r, a);
#elif defined(USE_FIELD_INV_NUM)
secp256k1_num_t n, m;
static const secp256k1_fe_t negone = SECP256K1_FE_CONST(
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFC2E
);
/* secp256k1 field prime, value p defined in "Standards for Efficient Cryptography" (SEC2) 2.7.1. */
static const unsigned char prime[32] = {
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
Expand All @@ -228,6 +232,10 @@ static void secp256k1_fe_inv_var(secp256k1_fe_t *r, const secp256k1_fe_t *a) {
secp256k1_num_mod_inverse(&n, &n, &m);
secp256k1_num_get_bin(b, 32, &n);
VERIFY_CHECK(secp256k1_fe_set_b32(r, b));
/* Verify the result is the (unique) valid inverse using non-GMP code. */
secp256k1_fe_mul(&c, &c, r);
secp256k1_fe_add(&c, &negone);
CHECK(secp256k1_fe_normalizes_to_zero_var(&c));
#else
#error "Please select field inverse implementation"
#endif
Expand Down
6 changes: 5 additions & 1 deletion src/scalar_impl.h
Expand Up @@ -240,12 +240,16 @@ static void secp256k1_scalar_inverse_var(secp256k1_scalar_t *r, const secp256k1_
#elif defined(USE_SCALAR_INV_NUM)
unsigned char b[32];
secp256k1_num_t n, m;
secp256k1_scalar_get_b32(b, x);
secp256k1_scalar_t t = *x;
secp256k1_scalar_get_b32(b, &t);
secp256k1_num_set_bin(&n, b, 32);
secp256k1_scalar_order_get_num(&m);
secp256k1_num_mod_inverse(&n, &n, &m);
secp256k1_num_get_bin(b, 32, &n);
secp256k1_scalar_set_b32(r, b, NULL);
/* Verify that the inverse was computed correctly, without GMP code. */
secp256k1_scalar_mul(&t, &t, r);
CHECK(secp256k1_scalar_is_one(&t));
#else
#error "Please select scalar inverse implementation"
#endif
Expand Down

0 comments on commit 36b305a

Please sign in to comment.