Feature #10849
closedAdding an alphanumeric function to SecureRandom
Description
It would be handy to have a method that produces a random alphanumeric string.
Files
Updated by andrewcbutterfield@gmail.com (Andrew Butterfield) almost 10 years ago
- File securerandom.txt securerandom.txt added
Updated by andrewcbutterfield@gmail.com (Andrew Butterfield) almost 10 years ago
- File securerandom.patch securerandom.patch added
Updated by nobu (Nobuyoshi Nakada) almost 10 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
length.times.map {source[random_number(size)]}.join('')
end
GRAPH = [*'!'..'~']
def self.graph(length)
choose(GRAPH, length)
end
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)
end
Updated by andrewcbutterfield@gmail.com (Andrew Butterfield) almost 10 years ago
- File securerandom.patch securerandom.patch added
- File test_securerandom.patch test_securerandom.patch added
This is a fantastic interface and I really like the choose method.
Updated by recursive-madman (Recursive Madman) almost 10 years ago
Suggestion: Rename graph
to printable
and possibly add an :allow_space
option?
Updated by kosaki (Motohiro KOSAKI) almost 10 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 7 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) about 7 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.
Updated by nobu (Nobuyoshi Nakada) about 3 years ago
- Related to Feature #18183: make SecureRandom.choose public added