Class: RandomStringGenerator

Inherits:
Object
  • Object
show all
Includes:
CharacterRanges
Defined in:
lib/random_string_generator.rb

Overview

RandomStringGenerator Class

RandomStringGenerator provides the functionality to generate random Strings. It could be called RandomPasswordGenerator; however, this is not a highly secure generator. It depends on the security of the rand() method. An acceptable usage of this might be the generation of temporary passwords. See the SECURITY_NOTES file.

Generating a Random Password

This is how to generate a random String with the default settings (see RandomStringGenerator.new for list of options)

rsg = RandomStringGenerator.new
str = rsg.generate => #<String>

This will generate a random String of length 10, with no duplicate characters, and not using an uppercase characters.

rsg = RandomStringGenerator.new( 10, :no_duplicates => true, :upper_alphas => false )
str = rsg.generate => #<String>

Changing the length and options between generations

rsg = RandomStringGenerator.new
str = rsg.generate

Now change the options and length and call generate

rsg.set_options( :special => 'qwerty', :no_duplicates => true)
rsg.length = 6
str = rsg.generate

Generate a WEP key

This will generate a 64 bit WEP key in hexidecimal format

wep_64b_hex = RandomStringGenerator.generate_wep( 64 )

This will generate a 128 bit WEP key in ASCII format. (Note that ASCII WEP keys are not as secure as hexidecimal keys)

wep_128b_ascii = RandomStringGenerator.generate_wep( 128, :ascii )

Shuffle a String

You can shuffle a string inplace (destructively) or you can shuffle the String into a new one.

Inplace:

str = 'foobar'
RandomStringGenerator.shuffle_string! str

str is now shuffled.

New String:

str = 'foobar'
new_str = RandomStringGenerator.shuffle_string str

str is not touched new_str is a shuffled version of str

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from CharacterRanges

#range, #range_all, #range_all_except_quotes, #range_backtick, #range_double_quotes, #range_lower_alphas, #range_numerals, #range_single_quotes, #range_symbols, #range_upper_alphas

Constructor Details

#initialize(len = 8, options = {}) ⇒ RandomStringGenerator

Initializes a new random string generator.

len is the length of the string you wish to have generated. Default is 8.

Options:

:no_duplicates

no duplicate characters, default is false

:lower_alphas

include lower alpha characters, default is true

:upper_alphas

include upper alpha characters, default is true

:numerals

include numeral characters, default is true

:symbols

include symbol characters, default is false

:single_quotes

include single quote characters, default is false

:double_quotes

include double quote characters, default is false

:backtick

include tick characters, default is false

:special

use a special string or array of ranges, overrides all other inclusion options



111
112
113
114
115
116
117
118
# File 'lib/random_string_generator.rb', line 111

def initialize( len = 8, options = {} )
  @length = len
  @options = { :lower_alphas => true,
    :upper_alphas => true,
    :numerals     => true,
    :no_duplicates=> false}.merge options
  
end

Instance Attribute Details

#lengthObject

Returns the value of attribute length.



91
92
93
# File 'lib/random_string_generator.rb', line 91

def length
  @length
end

#optionsObject (readonly)

Returns the value of attribute options.



92
93
94
# File 'lib/random_string_generator.rb', line 92

def options
  @options
end

Class Method Details

.generate_wep(bits, output = :hex) ⇒ Object

Generates a WEP key

bits: The number of bits for the encryption policy (ie. 64, 128, 152, 256)

output

Either :hex or :ascii (hex is more secure)



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/random_string_generator.rb', line 230

def self.generate_wep( bits, output = :hex )
  raise "Not a valid number of bits for a WEP key." unless [64,128,152,256].include? bits
  
  case output
  when :hex
    rsg = RandomStringGenerator.new((bits-24)/8, :special => [0..0xff])
    key = rsg.generate
    return key.unpack("H#{key.length*2}").at(0) if output == :hex
  when :ascii
    rsg = RandomStringGenerator.new((bits-24)/8, :special => [0x20..0x7e])
    key = rsg.generate
    return key
  else
    raise "Invalid output type."
  end
end

.shuffle_string(str) ⇒ Object

Returns a shuffled version of the given string.



194
195
196
# File 'lib/random_string_generator.rb', line 194

def self.shuffle_string( str )
  RandomStringGenerator.shuffle_string!( str.dup )
end

.shuffle_string!(str) ⇒ Object

Shuffles the given string (destructively aka. inplace)



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/random_string_generator.rb', line 169

def self.shuffle_string!( str )
  scramblers = Array.new(8)
  for i in 0...(str.length/2)
    scrambler_1 = rand(0xffffffff)
    scrambler_2 = rand(0xffffffff)
    for j in 0...4
      scramblers[j] = ((scrambler_1 & (0xff<<j*8)) >> j*8) % str.length
    end
    for j in 4...8 
      scramblers[j] = ((scrambler_2 & (0xff<<(j-4)*8)) >> (j-4)*8) % str.length
      # offset the wrap around to the end of the string
      scramblers[j] = (scramblers[j] + (0xff%str.length)) % str.length
    end
    
    # do the scrambling
    t = str[scramblers[0]]
    7.times { |j| str[scramblers[j]] = str[scramblers[j+1]] }
    str[scramblers[7]] = t
  end
  return str
end

Instance Method Details

#generateObject

Generate a password.



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/random_string_generator.rb', line 132

def generate
  set_characters_array
  
  # safety check for no_duplicates running out of characters
  if @options[:no_duplicates] && @characters.length < @length
    raise RuntimeError, "Too few options to have no duplicates."
  end
  shuffle_characters_array
  
  # generate the password
  p = String.new
  for i in 0...@length
    p << rand_char( @options[:noduplicates] )
  end
  return RandomStringGenerator.shuffle_string!(p)
end

#rand_char(delete_after_get = false) ⇒ Object

Get a random character from the characters array. Set the parameter to true to remove the character from the list after it’s been returned.



153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/random_string_generator.rb', line 153

def rand_char( delete_after_get = false )
  i = rand_index
  end_i = i + @characters.length
  
  until @characters[ i % @characters.length ].ord > 0 do # Walk until you find a non-0 character
    raise "No more characters." if i == end_i
    i += 1
  end
  c = @characters[ i % @characters.length ].chr # c is now the character we will return
  @characters[ i % @characters.length ] = 0.chr if delete_after_get # set the character to 0 (indicating deletedness)
  return c
end

#set_characters_arrayObject

Set the characters array to the set that we can use to generate a new password.



209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/random_string_generator.rb', line 209

def set_characters_array
  if @options.has_key? :special # set to special if it's there
    set_characters_from_special( @options[:special] )
  else # set by the given ranges
    ranges = Array.new
    @options.each do |opt, val| # run through options
      unless opt == :length || opt == :no_duplicates || val == false 
        ranges << self.send("range_#{opt.to_s}")
      end
    end
    set_characters_from_ranges ranges.flatten
  end
end

#set_option(opts = {}) ⇒ Object

Set the given options in

See RandomStringGenerator.new for the list of options.



125
126
127
# File 'lib/random_string_generator.rb', line 125

def set_option( opts = {} )
  @options.merge!( opts )
end

#shuffle_characters_arrayObject

Scramble the characters array



201
202
203
# File 'lib/random_string_generator.rb', line 201

def shuffle_characters_array
  RandomStringGenerator.shuffle_string!( @characters )
end