views:

272

answers:

4

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?

A: 

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?

Neil N
I'm not a mathematician, but wouldn't one want to fit the number 52! into X number of bits. 52! fits into a space of 2^226. With byte alignment it would be 2^232. So yea, I could probably use 232 bits instead. Again, I'm just giving an example to get an idea and some extra information.
+2  A: 

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.

Brian
Not to get into the shuffling bit, but there are two other methods of shuffling that should be perfect given the proper setup/conditions. A weighted sort and randomly picking a "card" and placing it into a new pile. The Knuth Shuffle just happens to be "in place."
Knuth Shuffle is an in place method of randomly picking a card and placing it into a new pile, so I wouldn't count it as being a separate method. I do agree that weighted sort is a real alternative.
Brian
A: 

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

Joonas Pulakka
+4  A: 

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.

Jason