birarduh
birarduh

Reputation: 782

What's the most compact way to generate a random unsigned value up to 20 bytes in ruby?

For a rails application I am generating X509 certificates signed by my own CA. I understand that as per the X509 spec the serial number for the generated certificates should be unique within the CA.

Instead of keeping track of the already issued serial numbers it seems to me that I should be able to use SecureRandom to generate a random 20 bytes that is statistically improbable to collide, convert that to a positive Bignum and set that as the serial number for any cert I generate.

What's the most compact way to do that?

So far this is what I have come up with:

SecureRandom.hex(20).unpack('c*').inject { |r, n| r << 8 | n }

Upvotes: 0

Views: 218

Answers (1)

Matt
Matt

Reputation: 20786

An improvement:

SecureRandom.random_bytes(20).unpack('C*').inject { |r,n| r << 8 | n }

The problem with using hex(20).unpack('c*') is that it's interpreting each hex digit as a byte so you're not getting the full 8-bit entropy, plus it's giving you 40 hex digits so the final number is unnecessarily long. Compare the lengths generated by this method, vs the question.


2nd Answer

There's already a function directly for this:

SecureRandom.random_number(1<<160)

160 bits = 20 bytes.

Upvotes: 2

Related Questions