我目前正在为“A”生成一个8字符伪随机大写字符串。。“Z”:
value = ""; 8.times{value << (65 + rand(25)).chr}
但它看起来不干净,而且不能作为参数传递,因为它不是一个单独的语句。要获取混合大小写字符串“a”。。“z”加“A”。。“Z”,我将其更改为:
value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}
但它看起来像垃圾。
有人有更好的方法吗?
我目前正在为“A”生成一个8字符伪随机大写字符串。。“Z”:
value = ""; 8.times{value << (65 + rand(25)).chr}
但它看起来不干净,而且不能作为参数传递,因为它不是一个单独的语句。要获取混合大小写字符串“a”。。“z”加“A”。。“Z”,我将其更改为:
value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr}
但它看起来像垃圾。
有人有更好的方法吗?
当前回答
从Ruby 2.5开始,使用SecureRandom.andlettery非常简单:
len = 8
SecureRandom.alphanumeric(len)
=> "larHSsgL"
它生成包含A-Z、A-Z和0-9的随机字符串,因此应适用于大多数用例。它们是随机安全生成的,这可能也是一个好处。
这是一个基准,用于将其与支持率最高的解决方案进行比较:
require 'benchmark'
require 'securerandom'
len = 10
n = 100_000
Benchmark.bm(12) do |x|
x.report('SecureRandom') { n.times { SecureRandom.alphanumeric(len) } }
x.report('rand') do
o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten
n.times { (0...len).map { o[rand(o.length)] }.join }
end
end
user system total real
SecureRandom 0.429442 0.002746 0.432188 ( 0.432705)
rand 0.306650 0.000716 0.307366 ( 0.307745)
因此,rand解决方案只需要SecureRandom时间的3/4。如果您生成大量字符串,这可能很重要,但如果您只是时不时地创建一些随机字符串,我会始终使用更安全的实现,因为它也更容易调用,更显式。
其他回答
下面是另一种方法:
它使用安全随机数生成器而不是rand()可用于URL和文件名包含大写、小写字符和数字具有不包含不明确字符I0l01的选项
需要“安全”
def secure_random_string(length = 32, non_ambiguous = false)
characters = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
%w{I O l 0 1}.each{ |ambiguous_character|
characters.delete ambiguous_character
} if non_ambiguous
(0...length).map{
characters[ActiveSupport::SecureRandom.random_number(characters.size)]
}.join
end
我的2美分:
def token(length=16)
chars = [*('A'..'Z'), *('a'..'z'), *(0..9)]
(0..length).map {chars.sample}.join
end
我们一直在代码中使用这个:
class String
def self.random(length=10)
('a'..'z').sort_by {rand}[0,length].join
end
end
支持的最大长度是25(无论如何,我们只在默认情况下使用它,所以这不是问题)。
有人提到“…”如果你想完全避免产生冒犯性的词语,z是次优的。我们的一个想法是去掉元音,但你最终还是会得到WTFBBQ等。
从Ruby 2.5开始,使用SecureRandom.andlettery非常简单:
len = 8
SecureRandom.alphanumeric(len)
=> "larHSsgL"
它生成包含A-Z、A-Z和0-9的随机字符串,因此应适用于大多数用例。它们是随机安全生成的,这可能也是一个好处。
这是一个基准,用于将其与支持率最高的解决方案进行比较:
require 'benchmark'
require 'securerandom'
len = 10
n = 100_000
Benchmark.bm(12) do |x|
x.report('SecureRandom') { n.times { SecureRandom.alphanumeric(len) } }
x.report('rand') do
o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten
n.times { (0...len).map { o[rand(o.length)] }.join }
end
end
user system total real
SecureRandom 0.429442 0.002746 0.432188 ( 0.432705)
rand 0.306650 0.000716 0.307366 ( 0.307745)
因此,rand解决方案只需要SecureRandom时间的3/4。如果您生成大量字符串,这可能很重要,但如果您只是时不时地创建一些随机字符串,我会始终使用更安全的实现,因为它也更容易调用,更显式。
`pwgen 8 1`.chomp