From 9c696b523de502a966af283afcd7f7bceb5479d7 Mon Sep 17 00:00:00 2001 From: Barry Brown Date: Thu, 13 Jun 2024 06:49:14 +0000 Subject: [PATCH 1/3] Remove assumption of 26 as modulus --- src/core/Utils.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/Utils.mjs b/src/core/Utils.mjs index a9c381d7..707720cc 100755 --- a/src/core/Utils.mjs +++ b/src/core/Utils.mjs @@ -1275,7 +1275,7 @@ class Utils { static modInv(x, y) { x %= y; for (let i = 1; i < y; i++) { - if ((x * i) % 26 === 1) { + if ((x * i) % y === 1) { return i; } } From 8530c47cb8c92dc0ab3a9b93469c1c0a56e13465 Mon Sep 17 00:00:00 2001 From: Barry Brown Date: Thu, 13 Jun 2024 17:19:11 +0000 Subject: [PATCH 2/3] modInv uses Extended Euclidean Algorithm --- src/core/Utils.mjs | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/core/Utils.mjs b/src/core/Utils.mjs index 707720cc..08eadbf1 100755 --- a/src/core/Utils.mjs +++ b/src/core/Utils.mjs @@ -1266,19 +1266,26 @@ class Utils { /** * Finds the modular inverse of two values. + * Uses the Extended Euclidean Algorithm. * - * @author Matt C [matt@artemisbot.uk] - * @param {number} x - * @param {number} y - * @returns {number} + * @author Barry B [profbbrown@gmail.com] + * @param {number} a + * @param {number} n + * @returns {number|null} */ - static modInv(x, y) { - x %= y; - for (let i = 1; i < y; i++) { - if ((x * i) % y === 1) { - return i; - } + static modInv(a, n) { + let t = 0, newT = 1, r = n, newR = a; + + while (newR !== 0) { + const q = Math.floor(r / newR); + [t, newT] = [newT, t - q * newT]; + [r, newR] = [newR, r - q * newR]; } + + if (r > 1) return null; + if (t < 0) t = t + n; + + return t; } From bc559888e6bfa29091992b6058048caa6358fc01 Mon Sep 17 00:00:00 2001 From: Barry Brown Date: Thu, 13 Jun 2024 20:57:17 +0000 Subject: [PATCH 3/3] Returns undefined if not invertible --- src/core/Utils.mjs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/core/Utils.mjs b/src/core/Utils.mjs index 08eadbf1..851044c3 100755 --- a/src/core/Utils.mjs +++ b/src/core/Utils.mjs @@ -1265,13 +1265,14 @@ class Utils { /** - * Finds the modular inverse of two values. + * Calculates the modular multiplicative inverse of a (mod n). * Uses the Extended Euclidean Algorithm. + * https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm * * @author Barry B [profbbrown@gmail.com] * @param {number} a * @param {number} n - * @returns {number|null} + * @returns {number|undefined} The inverse of a (mod n), or undefined */ static modInv(a, n) { let t = 0, newT = 1, r = n, newR = a; @@ -1282,7 +1283,7 @@ class Utils { [r, newR] = [newR, r - q * newR]; } - if (r > 1) return null; + if (r > 1) return undefined; if (t < 0) t = t + n; return t;