Best method of generating a number with 256 random

2020-03-29 06:32发布

What is the best method of generating a number with 256 random bits?

Does concatenating random bytes work?


byte[] data = new byte[32];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(data); // should include zero bytes?
string number = BitConverter.ToString(data, 0).Replace("-", "");

Further more, would it be appropriate to sort a deck of cards using non-duplicates of these numbers?

4条回答
迷人小祖宗
2楼-- · 2020-03-29 06:43

Whether or not you can concatenate random bytes depends on the random number generator that you are using. Some random number generators exhibit serial correlation. For these random number generators, concatenating would be bad.

If you are using these random numbers for crypotgraphic purposes, you should look at Blum Blum Shub. Otherwise, look at the Mersenne Twister.

For shuffling a finite set, look at the Fisher-Yates shuffle.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-03-29 06:49

If the random byte generator is good, any method works equally well, and also your card shuffling approach is appropriate.

查看更多
走好不送
4楼-- · 2020-03-29 06:58

yes, concatenating random bytes would work.

EDIT: Not sure why you would need 256 bits to shuffle a deck of cards, can you expand on that part further?

查看更多
Bombasti
5楼-- · 2020-03-29 07:04

The correct way to shuffle a deck of cards is with a Knuth Shuffle. It's simple and perfect. Perfect meaning that all possible card orderings are equally likely, assuming use of a good RNG.

查看更多
登录 后发表回答