mercredi 25 janvier 2017

How can I securely randomize a Ruby array?

How can I use Ruby's Array.shuffle method with a secure random number generator?

The method can accept a random number generator as an argument. However, SecureRandom from the standard library is not actually a random number generator that can simply replace the Random class.

a = %w(Some data that needs to be randomized)
a.shuffle! # Not securely random

# Is this any good? I arbitrarily choose 2**32. Should it be something else?
a.shuffle!(random: Random.new(SecureRandom.random_number(2**32)))

I did find this example which simply re-implements the Array#shuffle method. However, I'd rather just pass in the correct random number generator into the existing (optimized) method rather than re-implementing my own.




Aucun commentaire:

Enregistrer un commentaire