Project

General

Profile

Feature #10849 ยป securerandom.patch

View differences:

lib/securerandom.rb
297 297
    ary[3] = (ary[3] & 0x3fff) | 0x8000
298 298
    "%08x-%04x-%04x-%04x-%04x%08x" % ary
299 299
  end
300

  
301
  # SecureRandom.choose generates a string that randomly draws from a source array of
302
  # characters.
303
  #
304
  # The argument _source_ specifies the array of characters from which to generate the
305
  # string. The argument _n_ specifies the length, in characters, of the string to be 
306
  # generated.
307
  #
308
  # If _n_ is not specified or is nil, 16 is assumed.
309
  # It may be larger in the future.
310
  #
311
  # The result may contain whatever characters are in the source array.
312
  #
313
  #   p SecureRandom.choose([*'l'..'r']) #=> "lmrqpoonmmlqlron"
314
  #   p SecureRandom.choose([*'0'..'9'], 5) #=> "27309"
315
  #
316
  # If a secure random number generator is not available,
317
  # +NotImplementedError+ is raised.
318
  def self.choose(source, n=nil)
319
    n = 16 if n.nil?
320
    size = source.size
321
    n.times.map {source[random_number(size)]}.join('')
322
  end
323

  
324
  GRAPH = [*'!'..'~'] unless defined? GRAPH
325
  # SecureRandom.graph generates a random graph string that contains all the printable
326
  # ASCII characters except for space.
327
  #
328
  # The argument _n_ specifies the length, in characters, of the string to be
329
  # generated.
330
  #
331
  # If _n_ is not specified or is nil, 16 is assumed.
332
  # It may be larger in the future.
333
  #
334
  # The result may contain all the printable ASCII characters except for space.
335
  #
336
  #   p SecureRandom.graph #=> "$|yjZXTSXL\Tg+ip"
337
  #   p SecureRandom.graph(10) #=> "<8Qz@py?LG"
338
  #
339
  # If a secure random number generator is not available,
340
  # +NotImplementedError+ is raised.
341
  def self.graph(n=nil)
342
    choose(GRAPH, n)
343
  end
344

  
345
  ALPHANUMERIC = [*'A'..'Z', *'a'..'z', *'0'..'9'] unless defined? ALPHANUMERIC
346
  # SecureRandom.alphanumeric generates a random alphanumeric string.
347
  #
348
  # The argument _n_ specifies the length, in characters, of the alphanumeric
349
  # string to be generated.
350
  #
351
  # If _n_ is not specified or is nil, 16 is assumed.
352
  # It may be larger in the future.
353
  #
354
  # The result may contain A-Z, a-z and 0-9.
355
  #
356
  #   p SecureRandom.alphanumeric #=> "2BuBuLf3WfSKyQbR"
357
  #   p SecureRandom.alphanumeric(10) #=> "i6K93NdqiH"
358
  #
359
  # If a secure random number generator is not available,
360
  # +NotImplementedError+ is raised.
361
  def self.alphanumeric(n=nil)
362
    choose(ALPHANUMERIC, n)
363
  end
300 364
end