2

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 2

5

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);
2

If you have web3 you can use randomHex from web3-utils.

web3.utils.randomHex(32)
> "0xa5b9d60f32436310afebcfda832817a68921beb782fabf7915cc0460b443116a"
1
  • 1
    And then use web3.utils.toBN() to convert it to a BN, if needed.
    – Pang
    Commented Apr 28, 2022 at 8:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.