3

I am creating a pastebin app and I want the pastes' IDs to be truly random. /dev/random on Linux (hosted on a Linux machine) uses noise so it's output is truly random.

Currently I use this code to generate the IDs:

self.guid = Digest::SHA1.hexdigest(Time.new.to_s + (0...50).map{ ('a'..'z').to_a[rand(26)] }.join)

Does Ruby's rand function use /dev/random, and if not how can I use /dev/random in Ruby? Thanks.

Guilherme Bernal
  • 8,183
  • 25
  • 43

2 Answers2

12

The hardly documented SecureRandom (standard lib in ruby 1.9.2) uses OpenSSL (which is faster than urandom), if not available it uses urandom, last it checks if win32's random is available. If none you'll get an error. It has nice features:

require 'securerandom'
puts SecureRandom.urlsafe_base64(50)
#=> thgv48AT_gGcYD3xx-lCqRWjoAFqN3pm2ZBKOZPZP2BC0aSMD5rXg1EaPzKLbJMMt4Y
puts SecureRandom.uuid
#=> 2670f82a-0aee-41a8-93c5-2d08e2c608db 

(uuid: RFC 4122)

steenslag
  • 79,051
  • 16
  • 138
  • 171
3

Nope, the documentation mentions a Mersenne twister, implying a software solution, not the random device.

However, it might use a device for seeding, depending on the version of Ruby that you are using and how it was compiled. A quick grep of the ruby-1.9.2-p0 source shows a few references to /dev/urandom (perhaps for OpenSolaris) which looks like that device will be used for seeding if the USE_DEV_URANDOM macro is defined.

You are better off reading from /dev/random directly if you really need that degree of randomness. This SO question should get you started.

Community
  • 1
  • 1
maerics
  • 151,642
  • 46
  • 269
  • 291