【问题标题】:Secure Password Generation With Random Chars使用随机字符生成安全密码
【发布时间】:2017-01-15 12:43:11
【问题描述】:

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

【问题讨论】:

  • 您的研究告诉了您什么?目前您的问题是要求我们推荐解决方案或页面。请阅读“How to Ask”,包括链接页面。

标签: ruby security password-generator


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      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 的上述加密安全版本,有些人are recommending

      用gemsimple-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。尽管它不包含特殊字符,但它只是一个微不足道的添加。如果您感兴趣,请随意提交问题。

      【讨论】:

        【解决方案4】:

        您可以使用 SecureRandom (docs):

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

        【讨论】:

        • 这只会在 46.875% 的时间内生成带有特殊字符的字符串。该角色有 2/64 的机会是 +/,乘以 15 为 0.46875。
        猜你喜欢
        • 2016-08-15
        • 2021-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-08
        • 1970-01-01
        • 2015-11-07
        • 2012-08-24
        相关资源
        最近更新 更多