How to generate random prime number?

Viewed 528

I am currently working on a JavaScript team project which involves cryptography.

I want my program to be as safe as possible, if possible industry-level safe, and as such I have been searching for community-approved implementations of random big prime number generation algorithms.

I explored Node.js Crypto, but I did not find a straightforward function that returns a random big probable prime number.

How can I use Node.js Crypto to solve this problem?

2 Answers

Since v15.8.0 Node.js built-in crypto module provides generatePrime and generatePrimeSync methods.

For example, to generate a 16-bit prime use:

const crypto = require('crypto');

let prime = crypto.generatePrimeSync(16, {bigint: true}); // 49597n

Since calculating large primes can take time, there is also an asynchronous option with a callback:

const crypto = require('crypto');

crypto.generatePrime(16, {bigint: true}, (err, prime) => {
    console.log(prime); // 60757n
});

Note: the bigint option is used to return a bigint instead of an ArrayBuffer

createDiffieHellman from Node's crypto module can do this:

const crypto = require('crypto');

let DH = crypto.createDiffieHellman(16); // bit length

let prime = DH.getPrime('hex');
let dec = parseInt(prime, 16);

console.log('prime:', prime); // prime: c803
console.log('dec:', dec); // dec: 51203
Related