1

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

  1. One byte = collection of 8 bits.
  2. Every alphanumeric character occupies 1 byte according to String#bytesize.
('a'..'z').chain('A'..'Z').chain('0'..'9').map(&:bytesize).uniq
# => [1]
  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...
  2. As a result, @anothermh's answer can be considered as an acceptable solution.

Marian13
  • 7,740
  • 2
  • 47
  • 51

1 Answers1

3

Use SecureRandom.

First, make sure you require it:

require 'securerandom'

Then you can generate values:

SecureRandom.alphanumeric(10)
=> "hxYolwzk0P"

Change 10 to whatever length you require.

It's worth pointing out that the example you used was returning not alphanumeric but hexadecimal values. If you specifically require hex then you can use:

SecureRandom.hex(10)
=> "470eb1d8daebacd20920"
anothermh
  • 9,815
  • 3
  • 33
  • 52
  • Thanks for your answer. Could you also provide a link to `SecureRandom.alphanumeric` docs. I would like to be sure that it accepts bit length as a parameter. – Marian13 Jul 01 '20 at 18:04
  • `SecureRandom` is extended by `Random::Formatter` which provides the methods: https://docs.ruby-lang.org/en/2.7.0/Random/Formatter.html#method-i-alphanumeric For `alphanumeric` it is the string length, for `hex` is it bit length. – anothermh Jul 01 '20 at 18:28
  • @Marian13 Has this answer provided you with the desired solution? – anothermh Jul 11 '20 at 23:56
  • @ anothermh Yes, thank you. Your answer helped me to find an acceptable solution. – Marian13 Jul 12 '20 at 21:07
  • Great, glad to hear it! – anothermh Jul 12 '20 at 22:23