user2977636
user2977636

Reputation: 2286

Secure Password Generation With Random Chars

I am trying to generate a random password that contains special chars using ruby. I would like to know if there is a standard for generating such passwords. I have considered using a weighted probability distribution and assigning weights such that there is a higher probability of picking special chars from , but I am not sure if this is a widely-accepted standard.

Upvotes: 9

Views: 13800

Answers (4)

h6ah4i
h6ah4i

Reputation: 395

The ruby's built-in SecureRandom module has convenient methods since 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

Upvotes: 5

Mario Ruiz
Mario Ruiz

Reputation: 72

The easiest way is by using the string_pattern gem https://github.com/MarioRuiz/string_pattern

This will generate 1000 unique strings from 6 to 20 characters including letters, and force to include special characters and numbers

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

Upvotes: -1

DiegoSalazar
DiegoSalazar

Reputation: 13531

Ruby comes with just such a module SecureRandom. You can generate random strings:

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=="

There is now a cryptographically secure version of the above called SysRandom which some people are recommending.

With the gem simple-password-gen You can also generate random and pronounceable passwords:

require "simple-password-gen"

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

Finally, and just for fun (I recommend SysRandom), I wrote a small gem a while back to generate random strings based on template strings. Although it doesn't include special chars, it would be a trivial addition. Feel free to submit an issue for it if it interests you.

Upvotes: 16

lcguida
lcguida

Reputation: 3847

You can use SecureRandom (docs):

require 'securerandom'

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

Upvotes: 13

Related Questions