Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / functions / seeded_rand_string.rb
1 # @summary
2 #   Generates a consistent random string of specific length based on provided seed.
3 #
4 # @example Generate a consistently random string of length 8 with a seed:
5 #   seeded_rand_string(8, "${module_name}::redis_password")
6 #
7 # @example Generate a random string from a specific set of characters:
8 #   seeded_rand_string(5, '', 'abcdef')
9 Puppet::Functions.create_function(:seeded_rand_string) do
10   # @param length Length of string to be generated.
11   # @param seed Seed string.
12   # @param charset String that contains characters to use for the random string.
13   #
14   # @return [String] Random string.
15   dispatch :rand_string do
16     param 'Integer[1]', :length
17     param 'String', :seed
18     optional_param 'String[2]', :charset
19   end
20
21   def rand_string(length, seed, charset = nil)
22     require 'digest/sha2'
23
24     charset ||= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
25
26     random_generator = Random.new(Digest::SHA256.hexdigest(seed).to_i(16))
27
28     Array.new(length) { charset[random_generator.rand(charset.size)] }.join
29   end
30 end