Feature #10849

Adding an alphanumeric function to SecureRandom

Added by (Andrew Butterfield) over 5 years ago. Updated almost 3 years ago.

Target version:


It would be handy to have a method that produces a random alphanumeric string.


securerandom.txt (1.32 KB) securerandom.txt Git Diff (Andrew Butterfield), 02/12/2015 11:56 PM
securerandom.patch (1.32 KB) securerandom.patch (Andrew Butterfield), 02/13/2015 12:02 AM
securerandom.patch (2.49 KB) securerandom.patch (Andrew Butterfield), 02/19/2015 08:14 PM
test_securerandom.patch (641 Bytes) test_securerandom.patch (Andrew Butterfield), 02/19/2015 08:15 PM

Updated by nobu (Nobuyoshi Nakada) over 5 years ago

The length of the result string is about 4/3 of n.

I don't like this interface.

  def self.choose(source, length)
    size = source.size {source[random_number(size)]}.join('')

  GRAPH = [*'!'..'~']
  def self.graph(length)
    choose(GRAPH, length)

  ALPHANUMERIC = [*'A'..'Z', *'a'..'z', *'0'..'9']
  # SecureRandom.alphanumeric generates a random alphanumeric string.
  # The argument _n_ specifies the length of the random number to be
  # generated.
  # The result may contain A-Z, a-z and 0-9.
  #   p SecureRandom.alphanumeric #=> "2BuBuLf3WfSKyQbRccA"
  #   p SecureRandom.alphanumeric #=> "6BbW0pxO0YENxn38HMUbcQ"
  # If a secure random number generator is not available,
  # +NotImplementedError+ is raised.
  def self.alphanumeric(length)
    choose(ALPHANUMERIC, length)

Updated by (Andrew Butterfield) over 5 years ago

This is a fantastic interface and I really like the choose method.

Updated by recursive-madman (Recursive Madman) over 5 years ago

Suggestion: Rename graph to printable and possibly add an :allow_space option?

Updated by kosaki (Motohiro KOSAKI) over 5 years ago

This proposal doesn't contain a use-case nor proposal justification. So, nobody can judge this is good interface or not.

Updated by f3ndot (Justin Bull) about 3 years ago

As an end user of Ruby, I'd like to be able to generate all sorts of cryptographically secure random characters. There's value in having only alphabetical or alphanumeric chars as they are slightly more human readable.

My use case is offline recovery codes that I expect individuals to write down.


Updated by akr (Akira Tanaka) almost 3 years ago

  • Status changed from Open to Closed

Applied in changeset trunk|r60297.

SecureRandom.alphanumeric implemented.

[ruby-core:68098] [Feature #10849] proposed by Andrew Butterfield.

SecureRandom.choose and SecureRandom.graph is not included.
(The implementation has SecureRandom.choose but it is private.)

I feel the method name, SecureRandom.choose, doesn't represent
the behavior well.

The actual use cases of SecureRandom.graph is not obvious.

Also available in: Atom PDF