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

8

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


你的研究告诉了你什么?目前你的问题要求我们推荐解决方案或页面。请阅读包括链接页面在内的"[ask]"。 - the Tin Man
4个回答

16
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),我写了一个小宝石来基于模板字符串生成随机字符串。虽然它不包括特殊字符,但这很容易添加。如果你感兴趣,随意提交问题。


13

你可以使用SecureRandom (文档):

require 'securerandom'

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

1
这将仅在46.875%的时间内生成带有特殊字符的字符串。字符为+/的概率为2/64,乘以15得到0.46875。 - Jimbali

4

自 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


-1

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接