Method: HenselCode::Tools#random_prime
- Defined in:
- lib/hensel_code/tools.rb
#random_prime(bits) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/hensel_code/tools.rb', line 19 def random_prime(bits) # The OpenSSL library only generates random primes from 16 bits on # The 3513 is the first 16-bit number # which means there are 3512 primes under 16 bits in length # Therefore for allowing values for the parameter 'bits' between 2 and 15, # we generate all primes from 2 to 15 bits using Ruby's Prime library # and select only those with bit length equal to the value of 'bits' # so we sample one element # We only do this if the value of 'bits' is less than 16, otherwise we # use OpenSSL to generate the prime if bits >= 2 && bits < 16 primes = Prime.first(3512) primes.select { |p| p.bit_length == bits }.sample elsif bits >= 16 OpenSSL::BN.generate_prime(bits).to_i else raise BadBitRangeForRandomPrime, "The bit length must be greater than or equal to 2" end end |