8

我正在尝试使用 ruby​​ 生成包含特殊字符的随机密码。我想知道是否有生成此类密码的标准。我考虑过使用加权概率分布并分配权重,以便从 中选择特殊字符的概率更高,但我不确定这是否是一个被广泛接受的标准。

4

4 回答 4

15

Ruby 就带有这样一个模块SecureRandom。您可以生成随机字符串:

require "securerandom"

SecureRandom.hex 1 # => "e1"
SecureRandom.hex 2 # => "dcdd"
SecureRandom.hex 3 # => "93edc6"
SecureRandom.hex 5 # => "01bf5657ce"
SecureRandom.hex 8 # => "3cc72f70146ea286"

SecureRandom.base64 2  # => "d5M="
SecureRandom.base64 3  # => "EJ1K"
SecureRandom.base64 5  # => "pEeGO68="
SecureRandom.base64 8  # => "muRa+tO0RqU="
SecureRandom.base64 13 # => "1f8y7xsvaCEw0hwkjg=="

现在有一个名为SysRandom的上述加密安全版本,有些人正在推荐它。

使用 gemsimple-password-gen您还可以生成随机且可发音的密码

require "simple-password-gen"

Password.random 8 # => "#TFJ)Vtz3"
Password.pronounceable 13 # => "vingastusystaqu"

最后,只是为了好玩(我推荐 SysRandom),不久前我写了一个小 gem 来生成基于模板字符串的随机字符串。尽管它不包含特殊字符,但它只是一个微不足道的添加。如果您感兴趣,请随意提交问题。

于 2016-09-07T18:22:07.693 回答
11

您可以使用 SecureRandom ( docs ):

require 'securerandom'

password = SecureRandom.base64(15)
# => "vkVuWvPUWSMcZf9nn/dO"
于 2016-09-07T18:21:16.817 回答
3

从 ruby​​ 2.5 开始,ruby 内置的SecureRandom模块具有方便的方法。

require "securerandom"

# If you need A-Za-z0-9
SecureRandom.alphanumeric(10)

# If you want to specify characters (excluding similar characters)
# However, this method is NOT PUBLIC and it might be changed someday.
SecureRandom.send(:choose, [*'A'..'Z', *'a'..'z', *'0'..'9'] - ['I', 'l', '1', 'O', '0'], 10)

# Old ruby compatible version
chars = [*'A'..'Z', *'a'..'z', *'0'..'9']
10.times.map { chars[SecureRandom.random_number(chars.length)] }.join

于 2021-08-31T14:11:31.873 回答
-1

最简单的方法是使用 string_pattern gem https://github.com/MarioRuiz/string_pattern

这将生成 1000 个 6 到 20 个字符(包括字母)的唯一字符串,并强制包含特殊字符和数字

require 'string_pattern'
1000.times {
    puts :"6-20:L/$N/&".gen 
}
于 2018-12-06T11:04:01.687 回答