# -*- coding: us-ascii -*-
# frozen_string_literal: true
require 'random/formatter'
# == Secure random number generator interface.
# This library is an interface to secure random number generators which are
# suitable for generating session keys in HTTP cookies, etc.
# You can use this library in your application by requiring it:
# It supports the following secure random number generators:
# SecureRandom is extended by the Random::Formatter module which
# defines the following methods:
# These methods are usable as class methods of SecureRandom such as
# If a secure random number generator is not available,
# +NotImplementedError+ is raised.
def gen_random_openssl(n)
@pid = 0 unless defined?(@pid)
now = Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond)
OpenSSL::Random.random_add([now, @pid, pid].join(""), 0.0)
seed = Random.urandom(16)
OpenSSL::Random.random_add(seed, 16)
return OpenSSL::Random.random_bytes(n)
def gen_random_urandom(n)
raise NotImplementedError, "No random device"
raise NotImplementedError, "Unexpected partial read from random device: only #{ret.length} for #{n} bytes"
# Check if Random.urandom is available
alias gen_random gen_random_urandom
raise NotImplementedError, "No random device"
alias gen_random gen_random_openssl
SecureRandom.extend(Random::Formatter)