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