Best method of generating a number with 256 random

2020-03-29 06:54发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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?



回答4:

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