@h0llyw00dzz/crypto-rand
Version:
Cryptographically secure random utilities for Node.js and browsers
436 lines • 18.6 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.isProbablePrime = isProbablePrime;
exports.isProbablePrimeEnhanced = isProbablePrimeEnhanced;
exports.modPow = modPow;
exports.modInverse = modInverse;
exports.isProbablePrimeAsync = isProbablePrimeAsync;
exports.isProbablePrimeEnhancedAsync = isProbablePrimeEnhancedAsync;
exports.gcd = gcd;
/**
* Internal math utilities for cryptographic operations.
* These functions are intended for internal use only within the crypto-rand package,
* such as for testing purposes.
*/
const crypto = __importStar(require("crypto"));
/**
* [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test)
*
* **Note:** If you understand how this works, it's unlike the situation described in Wikipedia: "For instance, in 2018, Albrecht et al.
* were able to construct composite numbers that many cryptographic libraries, such as OpenSSL and GNU GMP, declared as prime,
* demonstrating that these libraries were not implemented with an adversarial context in mind." ¯\_(ツ)_/¯
*
* @param n - The number to test for primality
* @param k - The number of iterations for the test (a.k.a accuracy 🎯)
* @param getRandomBytes - Function to generate random bytes (defaults to crypto.randomBytes)
* @param enhanced - Whether to use the enhanced [FIPS](https://en.wikipedia.org/wiki/Federal_Information_Processing_Standards) version
* @returns A boolean indicating whether the number is probably prime
*/
function isProbablePrime(n, k, getRandomBytes = crypto.randomBytes, enhanced = false) {
if (enhanced) {
return isProbablePrimeEnhanced(n, k, getRandomBytes);
}
else {
return isProbablePrimeStandard(n, k, getRandomBytes);
}
}
/**
* Standard implementation of the [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test)
*
* This function implements the classic Miller-Rabin algorithm for primality testing.
* It's used internally by the `isProbablePrime` function when the enhanced parameter is false.
*
* @param n - The number to test for primality
* @param k - The number of iterations for the test (higher values increase accuracy)
* @param getRandomBytes - Function to generate random bytes for witness selection
* @returns A boolean indicating whether the number is probably prime
*/
function isProbablePrimeStandard(n, k, getRandomBytes) {
// Handle small numbers
if (n <= 1n)
return false;
if (n <= 3n)
return true;
if (n % 2n === 0n)
return false;
// Write n-1 as 2ʳ × d where d is odd
let r = 0;
let d = n - 1n;
while (d % 2n === 0n) {
d /= 2n;
r++;
}
// ⚙️ Witness loop
for (let i = 0; i < k; i++) {
// Generate a random integer a in the range [2, n-2]
const randomBytes = getRandomBytes(64); // 64 bytes should be enough for most primes
let a = BigInt('0x' + randomBytes.toString('hex')) % (n - 4n) + 2n;
// Compute aᵈ mod n
let x = modPow(a, d, n);
if (x === 1n || x === n - 1n)
continue;
let continueWitness = false;
for (let j = 0; j < r - 1; j++) {
x = modPow(x, 2n, n);
if (x === n - 1n) {
continueWitness = true;
break;
}
}
if (continueWitness)
continue;
return false;
}
return true;
}
/**
* Enhanced implementation of the [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) following [FIPS 186-5](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-5.pdf) standard
*
* This function implements the enhanced version of the [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test)
* as specified in the [FIPS 186-5](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-5.pdf) standard.
* It provides stronger guarantees than the standard [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) by including additional
* checks such as [GCD](https://en.wikipedia.org/wiki/Greatest_common_divisor) verification between random witnesses and the tested number.
*
* @param n - The number to test for primality
* @param k - The number of iterations for the test (higher values increase accuracy)
* @param getRandomBytes - Function to generate random bytes for witness selection
* @returns A boolean indicating whether the number is probably prime according to [FIPS 186-5](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-5.pdf) criteria
*/
function isProbablePrimeEnhanced(n, k, getRandomBytes = crypto.randomBytes) {
// Handle small numbers
if (n <= 1n)
return false;
if (n <= 3n)
return true;
if (n % 2n === 0n)
return false;
// Write n-1 as 2ʳ × d where d is odd (step 1 and 2 in FIPS 186-5)
let a = 0;
let m = n - 1n;
while (m % 2n === 0n) {
m /= 2n;
a++;
}
// ⚙️ Witness loop (step 4 in FIPS 186-5)
//
// Note: This does not return multiple results with indicators, such as returning false with a reason STRING like "PROVABLY COMPOSITE WITH FACTOR," etc.
// This is designed to be simple and straightforward, avoiding the complexity overhead of handling multiple results.
for (let i = 0; i < k; i++) {
// Generate a random integer b in the range [2, n-2] (steps 4.1 and 4.2)
let b;
do {
const randomBytes = getRandomBytes(64); // 64 bytes should be enough for most primes
b = BigInt('0x' + randomBytes.toString('hex')) % (n - 1n);
} while (b <= 1n || b >= n - 1n);
// Step 4.3: Check if b and n have a common factor
const g = gcd(b, n);
if (g > 1n) {
return false;
}
// Step 4.5: Compute z = b^m mod n
let z = modPow(b, m, n);
// Step 4.6: If z = 1 or z = n-1, continue to next iteration
if (z === 1n || z === n - 1n)
continue;
// Step 4.7: For j = 1 to a-1
let j = 1;
let isComposite = true;
while (j < a) {
// Step 4.7.1 and 4.7.2: x = z, z = x^2 mod n
const x = z;
z = modPow(x, 2n, n);
// Step 4.7.3: If z = n-1, continue to next iteration
if (z === n - 1n) {
isComposite = false;
break;
}
// Step 4.7.4: If z = 1, go to step 4.12
if (z === 1n) {
// Step 4.12: g = GCD(x-1, n)
const g = gcd(x - 1n, n);
// Step 4.13: If g > 1, return PROVABLY COMPOSITE WITH FACTOR
if (g > 1n) {
return false;
}
// Step 4.14: Return PROVABLY COMPOSITE AND NOT A POWER OF A PRIME
return false;
}
j++;
}
// If we've gone through all iterations of j and z is not n-1 or 1
if (isComposite) {
// Steps 4.8-4.11 are handled implicitly in the loop above
// Step 4.12: g = GCD(z-1, n)
const g = gcd(z - 1n, n);
// Step 4.13: If g > 1, return PROVABLY COMPOSITE WITH FACTOR
if (g > 1n) {
return false;
}
// Step 4.14: Return PROVABLY COMPOSITE AND NOT A POWER OF A PRIME
return false;
}
}
// Step 5: Return PROBABLY PRIME
return true;
}
/**
* [Modular exponentiation](https://en.wikipedia.org/wiki/Modular_exponentiation): baseᵉˣᵖᵒⁿᵉⁿᵗ mod modulus
*
* @param base - The base value
* @param exponent - The exponent value
* @param modulus - The modulus value
* @returns The result of the modular exponentiation
*/
function modPow(base, exponent, modulus) {
if (modulus === 1n)
return 0n;
let result = 1n;
base = base % modulus;
while (exponent > 0n) {
if (exponent % 2n === 1n) {
result = (result * base) % modulus;
}
exponent = exponent >> 1n;
base = (base * base) % modulus;
}
return result;
}
/**
* Calculate the [modular multiplicative inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) using the [Extended Euclidean Algorithm](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm)
*
* **Note:** This is a helper function primarily intended for testing purposes.
* Not recommended for production use as it may be vulnerable to timing attacks.
*
* @param a - The number to find the inverse for
* @param m - The modulus
* @returns The [modular multiplicative inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) inverse of a modulo m
*/
function modInverse(a, m) {
// Extended Euclidean Algorithm to find modular multiplicative inverse
let [old_r, r] = [a, m];
let [old_s, s] = [1n, 0n];
let [old_t, t] = [0n, 1n];
while (r !== 0n) {
const quotient = old_r / r;
[old_r, r] = [r, old_r - quotient * r];
[old_s, s] = [s, old_s - quotient * s];
[old_t, t] = [t, old_t - quotient * t];
}
// If old_r != 1, then a and m are not coprime and inverse doesn't exist
if (old_r !== 1n) {
throw new Error('Modular inverse does not exist');
}
// Make sure the result is positive
return (old_s % m + m) % m;
}
/**
* Async version of [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test)
*
* **Note:** If you understand how this works, it's unlike the situation described in Wikipedia: "For instance, in 2018, Albrecht et al.
* were able to construct composite numbers that many cryptographic libraries, such as OpenSSL and GNU GMP, declared as prime,
* demonstrating that these libraries were not implemented with an adversarial context in mind." ¯\_(ツ)_/¯
*
* @param n - The number to test for primality
* @param k - The number of iterations for the test (a.k.a accuracy 🎯)
* @param getRandomBytesAsync - Async function to generate random bytes
* @param enhanced - Whether to use the enhanced [FIPS](https://en.wikipedia.org/wiki/Federal_Information_Processing_Standards) version
* @returns A Promise that resolves to a boolean indicating whether the number is probably prime
*/
async function isProbablePrimeAsync(n, k, getRandomBytesAsync, enhanced = false) {
if (enhanced) {
return isProbablePrimeEnhancedAsync(n, k, getRandomBytesAsync);
}
else {
return isProbablePrimeStandardAsync(n, k, getRandomBytesAsync);
}
}
/**
* Asynchronous implementation of the standard [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test)
*
* This function is the asynchronous version of `isProbablePrimeStandard`, implementing the classic
* Miller-Rabin algorithm for primality testing. It's used internally by the `isProbablePrimeAsync`
* function when the enhanced parameter is false.
*
* @param n - The number to test for primality
* @param k - The number of iterations for the test (higher values increase accuracy)
* @param getRandomBytesAsync - Async function to generate random bytes for witness selection
* @returns A Promise that resolves to a boolean indicating whether the number is probably prime
*/
async function isProbablePrimeStandardAsync(n, k, getRandomBytesAsync) {
// Handle small numbers
if (n <= 1n)
return false;
if (n <= 3n)
return true;
if (n % 2n === 0n)
return false;
// Write n-1 as 2ʳ × d where d is odd
let r = 0;
let d = n - 1n;
while (d % 2n === 0n) {
d /= 2n;
r++;
}
// ⚙️ Witness loop
for (let i = 0; i < k; i++) {
// Generate a random integer a in the range [2, n-2]
const randomBytes = await getRandomBytesAsync(64); // 64 bytes should be enough for most primes
let a = BigInt('0x' + randomBytes.toString('hex')) % (n - 4n) + 2n;
// Compute aᵈ mod n
let x = modPow(a, d, n);
if (x === 1n || x === n - 1n)
continue;
let continueWitness = false;
for (let j = 0; j < r - 1; j++) {
x = modPow(x, 2n, n);
if (x === n - 1n) {
continueWitness = true;
break;
}
}
if (continueWitness)
continue;
return false;
}
return true;
}
/**
* Asynchronous implementation of the enhanced [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) following [FIPS 186-5](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-5.pdf) standard
*
* This function is the asynchronous version of `isProbablePrimeEnhanced`, implementing the enhanced
* version of the [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) as specified in the
* [FIPS 186-5](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-5.pdf) standard.
* It provides stronger guarantees than the standard [Miller-Rabin primality test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) by including additional
* checks such as [GCD](https://en.wikipedia.org/wiki/Greatest_common_divisor) verification between random witnesses and the tested number.
*
* @param n - The number to test for primality
* @param k - The number of iterations for the test (higher values increase accuracy)
* @param getRandomBytesAsync - Async function to generate random bytes for witness selection
* @returns A Promise that resolves to a boolean indicating whether the number is probably prime according to [FIPS 186-5](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-5.pdf) criteria
*/
async function isProbablePrimeEnhancedAsync(n, k, getRandomBytesAsync) {
// Handle small numbers
if (n <= 1n)
return false;
if (n <= 3n)
return true;
if (n % 2n === 0n)
return false;
// Write n-1 as 2ʳ × d where d is odd (step 1 and 2 in FIPS 186-5)
let a = 0;
let m = n - 1n;
while (m % 2n === 0n) {
m /= 2n;
a++;
}
// ⚙️ Witness loop (step 4 in FIPS 186-5)
//
// Note: This does not return multiple results with indicators, such as returning false with a reason STRING like "PROVABLY COMPOSITE WITH FACTOR," etc.
// This is designed to be simple and straightforward, avoiding the complexity overhead of handling multiple results.
for (let i = 0; i < k; i++) {
// Generate a random integer b in the range [2, n-2] (steps 4.1 and 4.2)
let b;
do {
const randomBytes = await getRandomBytesAsync(64); // 64 bytes should be enough for most primes
b = BigInt('0x' + randomBytes.toString('hex')) % (n - 1n);
} while (b <= 1n || b >= n - 1n);
// Step 4.3: Check if b and n have a common factor
const g = gcd(b, n);
if (g > 1n) {
return false;
}
// Step 4.5: Compute z = b^m mod n
let z = modPow(b, m, n);
// Step 4.6: If z = 1 or z = n-1, continue to next iteration
if (z === 1n || z === n - 1n)
continue;
// Step 4.7: For j = 1 to a-1
let j = 1;
let isComposite = true;
while (j < a) {
// Step 4.7.1 and 4.7.2: x = z, z = x^2 mod n
const x = z;
z = modPow(x, 2n, n);
// Step 4.7.3: If z = n-1, continue to next iteration
if (z === n - 1n) {
isComposite = false;
break;
}
// Step 4.7.4: If z = 1, go to step 4.12
if (z === 1n) {
// Step 4.12: g = GCD(x-1, n)
const g = gcd(x - 1n, n);
// Step 4.13: If g > 1, return PROVABLY COMPOSITE WITH FACTOR
if (g > 1n) {
return false;
}
// Step 4.14: Return PROVABLY COMPOSITE AND NOT A POWER OF A PRIME
return false;
}
j++;
}
// If we've gone through all iterations of j and z is not n-1 or 1
if (isComposite) {
// Steps 4.8-4.11 are handled implicitly in the loop above
// Step 4.12: g = GCD(z-1, n)
const g = gcd(z - 1n, n);
// Step 4.13: If g > 1, return PROVABLY COMPOSITE WITH FACTOR
if (g > 1n) {
return false;
}
// Step 4.14: Return PROVABLY COMPOSITE AND NOT A POWER OF A PRIME
return false;
}
}
// Step 5: Return PROBABLY PRIME
return true;
}
/**
* Calculate the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) (GCD) of two numbers using the [Euclidean algorithm](https://en.wikipedia.org/wiki/Greatest_common_divisor#Euclidean_algorithm)
*
* @param a - First number
* @param b - Second number
* @returns The greatest common divisor of a and b
*/
function gcd(a, b) {
while (b !== 0n) {
const temp = b;
b = a % b;
a = temp;
}
return a;
}
//# sourceMappingURL=math_helper.js.map