使用随机字符生成安全密码

Secure Password Generation With Random Chars

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

您可以使用 SecureRandom (docs):

require 'securerandom'

password = SecureRandom.base64(15)
# => "vkVuWvPUWSMcZf9nn/dO"

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 which some people are recommending 的加密安全版本。

用gem simple-password-gen也可以生成random and pronounceable passwords:

require "simple-password-gen"

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

最后,为了好玩(我推荐 SysRandom),我写了一个小 gem 一段时间回到 generate random strings based on template strings。虽然它不包括特殊字符,但它是一个微不足道的添加。如果您感兴趣,请随时提交问题。

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

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

require 'string_pattern'
1000.times {
    puts :"6-20:L/$N/&".gen 
}

ruby 的内置 SecureRandom 模块自 ruby 2.5.

以来具有方便的方法
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