Skip to content

Instantly share code, notes, and snippets.

@DataWraith
Created July 23, 2011 15:59
Show Gist options
  • Save DataWraith/1101577 to your computer and use it in GitHub Desktop.
Save DataWraith/1101577 to your computer and use it in GitHub Desktop.
Simple random password generator. Bonus: Base62 encoder/decoder
#/usr/bin/env ruby
require 'securerandom'
ENTROPY_BITS = 256
# Generate a password with an entropy of #{ENTROPY_BITS} bits by encoding a large number
# from the secure random number generator as Base62. Base64 is avoided because some websites
# reject passwords that contain non-alphanumeric characters. This also makes copy&paste easy
# through automatic word-boundary detection (on doubleclick) in many application.
module Base62
ALPHABET = Hash[(0...62).to_a.zip((('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a))]
INV_ALPHABET = ALPHABET.invert
def self.encode(n)
to_encode = n.to_i
raise ::ArgumentError, "Must be a non-negative integer: #{n.inspect}" if to_encode < 0
result = ""
begin
result << ALPHABET[to_encode % 62]
to_encode /= 62
end while to_encode > 0
return result.reverse!
end
def self.decode(str)
result = 0
multiplier = 1
str.reverse.each_char do |c|
unless INV_ALPHABET.has_key?(c)
raise ::ArgumentError, "Invalid character inside Base62 encoded String: #{c.inspect}"
end
result += INV_ALPHABET[c] * multiplier
multiplier *= 62
end
result
end
end
puts Base62.encode(SecureRandom.random_number(2**ENTROPY_BITS))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment