2021年2月10日星期三

How do I get a random BigInt in a specific range (Dart)

I'm sorry if this question has been asked before but I cannot find any solution that helps me.

Basically, I have a huge number n where n is a 4000 bit number. Obviously, it won't fit in the 64 bits allowed by the primitive type int in Dart.

I need to find a random number g such that 2 ≤ g ≤ (n - 1). Is there a way I can generate such a random number?

My current solution:

void _generatePrivateKey() {    const numbers = '0123456789';    final halfOfNLength = N.toString().length ~/ 2; // Where `N` is `BigInt`    final length = _rand.nextInt(halfOfNLength) + halfOfNLength;    final buffer = StringBuffer();    for (var _ = 0; _ < length; _++) {      buffer.write(numbers[_rand.nextInt(numbers.length)]);    }    _privateKey = BigInt.parse(buffer.toString());  }  

I know it's not a good solution but that's all I have for now

https://stackoverflow.com/questions/66118748/how-do-i-get-a-random-bigint-in-a-specific-range-dart February 09, 2021 at 08:11PM

没有评论:

发表评论