I need to generate a uint256 random number offchain (in a Node.js client). Since BN
doesn't have a random()
function, what's the best way to do so?
2 Answers
You can use Node.js' crypto.randomBytes
to generate a cryptographically secure random number:
import { randomBytes } from 'crypto';
import BN from 'bn.js';
const value = randomBytes(32); // 32 bytes = 256 bits
// Value as native bigint
const bigInt = BigInt(`0x${value.toString('hex')}`);
// Value as BN.js number
const bn = new BN(value.toString('hex'), 16);
If you have web3 you can use randomHex from web3-utils.
web3.utils.randomHex(32)
> "0xa5b9d60f32436310afebcfda832817a68921beb782fabf7915cc0460b443116a"
-
1And then use
web3.utils.toBN()
to convert it to aBN
, if needed.– PangCommented Apr 28, 2022 at 8:09