From ed9d8c1ebb2845e8b8913727dba7b0bc746f0168 Mon Sep 17 00:00:00 2001 From: Jochen Hoenicke Date: Fri, 30 Jan 2015 22:27:18 +0100 Subject: [PATCH] Fix RFC6979 generation of k. The standard says: step h: Set T to the empty sequence. while tlen < qlen V = HMAC_K(V) T = T || V k = bits2int(T) in this case (HMAC-SHA256, qlen=256bit) this simplifies to V = HMAC_K(V) T = V k = bits2int(T) and T can be omitted. The old code (wrong) did: T = HMAC_K(V) k = bits2int(T) Note that V will only be used again if the first k is out of range. Thus, the old code produced the right result with a very high probability. --- ecdsa.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ecdsa.c b/ecdsa.c index a4a6c1acc..e17a4a7e9 100644 --- a/ecdsa.c +++ b/ecdsa.c @@ -256,7 +256,7 @@ int generate_k_random(bignum256 *k) { int generate_k_rfc6979(bignum256 *secret, const uint8_t *priv_key, const uint8_t *hash) { int i; - uint8_t v[32], k[32], bx[2*32], buf[32 + 1 + sizeof(bx)], t[32]; + uint8_t v[32], k[32], bx[2*32], buf[32 + 1 + sizeof(bx)]; bignum256 z1; memcpy(bx, priv_key, 32); @@ -280,8 +280,8 @@ int generate_k_rfc6979(bignum256 *secret, const uint8_t *priv_key, const uint8_t hmac_sha256(k, sizeof(k), v, sizeof(k), v); for (i = 0; i < 10000; i++) { - hmac_sha256(k, sizeof(k), v, sizeof(v), t); - bn_read_be(t, secret); + hmac_sha256(k, sizeof(k), v, sizeof(v), v); + bn_read_be(v, secret); if ( !bn_is_zero(secret) && bn_is_less(secret, &order256k1) ) { return 0; // good number -> no error }