Skip to content

Instantly share code, notes, and snippets.

@hyjk2000
Created March 21, 2018 03:10
Show Gist options
  • Save hyjk2000/07de7e4cbd3464046b979a8c6bdc18da to your computer and use it in GitHub Desktop.
Save hyjk2000/07de7e4cbd3464046b979a8c6bdc18da to your computer and use it in GitHub Desktop.
Generate Random Password with SecureRandom
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