I am trying to solve the following problem using Ruby:
I have a requirement to generate strings with variable bits length which contain only alphanumeric characters.
Here is what I have already found:
Digest::SHA2.new(bitlen = 256).to_s
# => "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
It does exactly what I need, but it accepts only 256, 384, and 512 as bitlen
.
Does anybody aware of any alternatives?
Thanks in advance.
Update
- One byte = collection of 8 bits.
- Every alphanumeric character occupies 1 byte according to String#bytesize.
('a'..'z').chain('A'..'Z').chain('0'..'9').map(&:bytesize).uniq
# => [1]
Based on the facts mentioned above, we can suppose that
SecureRandom.alphanumeric(1)
generates an alphanumeric string with 8 bits length.SecureRandom.alphanumeric(2)
generates an alphanumeric string with 16 bits length.SecureRandom.alphanumeric(3)
generates an alphanumeric string with 24 bits length.- And so on...
As a result, @anothermh's answer can be considered as an acceptable solution.