From a0e9c608baac5230fa7ca90c01491e00339a1633 Mon Sep 17 00:00:00 2001 From: Ilya Chesnokov Date: Wed, 7 Aug 2019 18:42:55 +0300 Subject: [PATCH] DSA: Fix intermittent generation of invalid signatures (#938) --- src/crypto/public_key/dsa.js | 11 ++++------- src/util.js | 10 ---------- 2 files changed, 4 insertions(+), 17 deletions(-) diff --git a/src/crypto/public_key/dsa.js b/src/crypto/public_key/dsa.js index 3cab2d84..e0bc9db0 100644 --- a/src/crypto/public_key/dsa.js +++ b/src/crypto/public_key/dsa.js @@ -62,9 +62,7 @@ export default { // of leftmost bits equal to the number of bits of q. This (possibly // truncated) hash function result is treated as a number and used // directly in the DSA signature algorithm. - const h = new BN( - util.getLeftNBits(hashed, q.bitLength())) - .toRed(redq); + const h = new BN(hashed.subarray(0, q.byteLength())).toRed(redq); // FIPS-186-4, section 4.6: // The values of r and s shall be checked to determine if r = 0 or s = 0. // If either r = 0 or s = 0, a new value of k shall be generated, and the @@ -85,8 +83,8 @@ export default { break; } return { - r: r.toArrayLike(Uint8Array), - s: s.toArrayLike(Uint8Array) + r: r.toArrayLike(Uint8Array, 'be', q.byteLength()), + s: s.toArrayLike(Uint8Array, 'be', q.byteLength()) }; }, @@ -111,8 +109,7 @@ export default { } const redp = new BN.red(p); const redq = new BN.red(q); - const h = new BN( - util.getLeftNBits(hashed, q.bitLength())); + const h = new BN(hashed.subarray(0, q.byteLength())); const w = s.toRed(redq).redInvm(); // s**-1 mod q if (zero.cmp(w) === 0) { util.print_debug("invalid DSA Signature"); diff --git a/src/util.js b/src/util.js index 3a2f6430..af226453 100644 --- a/src/util.js +++ b/src/util.js @@ -466,16 +466,6 @@ export default { }); }, - getLeftNBits: function (array, bitcount) { - const rest = bitcount % 8; - if (rest === 0) { - return array.subarray(0, bitcount / 8); - } - const bytes = (bitcount - rest) / 8 + 1; - const result = array.subarray(0, bytes); - return util.shiftRight(result, 8 - rest); // +String.fromCharCode(string.charCodeAt(bytes -1) << (8-rest) & 0xFF); - }, - // returns bit length of the integer x nbits: function (x) { let r = 1;