Skip to content
Snippets Groups Projects
Commit aee8e4bc authored by ziggy's avatar ziggy Committed by ziggy
Browse files

add RandomCode

parent ae870486
No related branches found
No related tags found
No related merge requests found
require 'securerandom'
#
#
# Generates a random code in which there are no ambiguous characters.
# This way, no one has to puzzle if that is an 'l' or a '1'.
#
# With only lowercase and no ambiguous characters, the entropy of strings
# generated with RandomCode is lower than a string with capital letters
# and confusing characters. To compensate, you should pick a longer string.
#
# Entropy is:
#
# possible_chars = 32
# Math.log(length**possible_chars, 2)
#
# length 8 => 96 bits
# length 9 => 101 bits
# length 10 => 106 bits
# length 11 => 110 bits
# length 12 => 114 bits
# length 13 => 118 bits
# length 14 => 121 bits
# length 15 => 125 bits
# length 16 => 128 bits
# length 17 => 130 bits
# length 18 => 133 bits
# length 19 => 135 bits
# length 20 => 138 bits
#
module RandomCode
POSSIBLE = %w[a b c d e f g h i j k m n p q r s t u v w x y z 2 3 4 5 6 7 8 9]
def self.entropy(length)
Math.log(length ** POSSIBLE.length, 2).truncate
end
def self.create(length, split=nil)
possible = POSSIBLE.shuffle
str = SecureRandom.random_bytes(length).each_byte.map {|byte|
possible[byte % possible.length]
}.join
if split
return str.scan(/.{#{split}}/).join('-')
else
return str
end
end
end
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment