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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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