Skip to content

Instantly share code, notes, and snippets.

@namelessjon
Created January 28, 2016 13:41
Show Gist options
  • Save namelessjon/f54651bcd1c609821be2 to your computer and use it in GitHub Desktop.
Save namelessjon/f54651bcd1c609821be2 to your computer and use it in GitHub Desktop.
Generate random passwords according to a given pattern
#!/usr/bin/ruby
# Generate random passwords according to guidance in
# https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/458857/Password_guidance_-_simplifying_your_approach.pdf
require 'securerandom'
module PassGen
VOWELS = %w{a i e o u}.map { |l| l.freeze }.freeze
CONSONANTS = (('a'..'z').to_a - VOWELS).map { |l| l.freeze }.freeze
SYMBOLS = ['!', '$', '%', '^', '&', '*', '+', '-', '_', '?', '@', '#', '~', '.', ',', '=', '"', '\\', '/', '<', '>', ':', ';'].map { |l| l.freeze }.freeze
module_function
def vowel
VOWELS[SecureRandom.random_number(VOWELS.size)]
end
def consonant
CONSONANTS[SecureRandom.random_number(CONSONANTS.size)]
end
def number
SecureRandom.random_number(10)
end
def symbol
SYMBOLS[SecureRandom.random_number(SYMBOLS.size)]
end
def password_from_pattern(pattern='cvc')
pattern.downcase.gsub(/./) { |l|
case l
when 'c'
consonant
when 'v'
vowel
when 'n'
number
when 's'
symbol
else
l
end
}
end
def password(n = 4, pattern = 'cvc', join = '-')
password_from_pattern(n.times.map { |_| pattern }.join(join))
end
end
if $0 == __FILE__
require 'optparse'
Options = Struct.new(:pattern, :count)
class Parser
def self.parse(options)
args = Options.new("cvc-cvc-cvc-cvc", 1)
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: #{__FILE__} [options]"
opts.on("-pPATTERN", "--pattern=PATTERN", "Pattern for generated passwords") do |pattern|
args.pattern = pattern
end
opts.on("-cCOUNT", "--count=COUNT", "number of passwords to generate") do |c|
args.count = c.to_i
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
end
opt_parser.parse!(options)
return args
end
end
options = Parser.parse ARGV
options.count.times do
puts PassGen.password_from_pattern(options.pattern)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment