Created
March 21, 2018 03:10
-
-
Save hyjk2000/07de7e4cbd3464046b979a8c6bdc18da to your computer and use it in GitHub Desktop.
Generate Random Password with SecureRandom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'securerandom' | |
class PasswordGen | |
ALPHANUMERIC = ((48..57).to_a + (65..90).to_a + (97..122).to_a).pack('c*').freeze | |
SYMBOL = ((33..47).to_a + (58..64).to_a + (91..96).to_a + (123..126).to_a).pack('c*').freeze | |
attr_reader :length, :alphanumeric, :symbol | |
def initialize(length: 20, alphanumeric: true, symbol: true) | |
@length = length.to_i | |
@alphanumeric = alphanumeric | |
@symbol = symbol | |
end | |
def generate | |
Array.new(length) do | |
index = SecureRandom.random_number(char_table.length) | |
char_table[index] | |
end.join | |
end | |
private | |
def char_table | |
@char_table ||= "#{ALPHANUMERIC if alphanumeric}#{SYMBOL if symbol}".chars.shuffle.join | |
end | |
end | |
print PasswordGen.new.generate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment