public
Description: Ruby on Rails
Homepage: http://rubyonrails.org
Clone URL: git://github.com/rails/rails.git
Deprecate Rails::SecretKeyGenerator in favor of ActiveSupport::SecureRandom.

SecureRandom has a few minor security enhancements and can be used as a drop-in 
replacement

Signed-off-by: Michael Koziarski <michael@koziarski.com>
[#913 state:committed]
Hongli Lai (Phusion (author)
Wed Aug 27 03:42:08 -0700 2008
NZKoz (committer)
Wed Aug 27 06:08:16 -0700 2008
commit  b3411ff59eb1e1c31f98f58f117a2ffaaf0c3ff5
tree    c0bacd1a0ffa73149ce3eb81b5ef6a345093147d
parent  9dbde4f5cbd0617ee6cce3e41d41335f9c9ce3fd
...
55
56
57
 
 
58
59
60
...
55
56
57
58
59
60
61
62
0
@@ -55,6 +55,8 @@ require 'active_support/base64'
0
 
0
 require 'active_support/time_with_zone'
0
 
0
+require 'active_support/secure_random'
0
+
0
 I18n.populate do
0
   I18n.load_translations File.dirname(__FILE__) + '/active_support/locale/en-US.yml'
0
 end
...
1
2
3
4
5
6
...
36
37
38
39
 
40
41
42
...
1
2
 
3
4
5
...
35
36
37
 
38
39
40
41
0
@@ -1,6 +1,5 @@
0
 require 'rbconfig'
0
 require 'digest/md5' 
0
-require 'rails_generator/secret_key_generator'
0
 
0
 class AppGenerator < Rails::Generator::Base
0
   DEFAULT_SHEBANG = File.join(Config::CONFIG['bindir'],
0
@@ -36,7 +35,7 @@ class AppGenerator < Rails::Generator::Base
0
     md5 << @app_name
0
 
0
     # Do our best to generate a secure secret key for CookieStore
0
-    secret = Rails::SecretKeyGenerator.new(@app_name).generate_secret
0
+    secret = ActiveSupport::SecureRandom.hex(64)
0
 
0
     record do |m|
0
       # Root directory and all subdirectories.
...
5
6
7
 
 
 
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
 
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
...
5
6
7
8
9
10
11
 
 
12
 
13
14
15
16
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
21
0
@@ -5,160 +5,17 @@ module Rails
0
   #
0
   #   generator = Rails::SecretKeyGenerator("some unique identifier, such as the application name")
0
   #   generator.generate_secret     # => "f3f1be90053fa851... (some long string)"
0
+  #
0
+  # This class is *deprecated* in Rails 2.2 in favor of ActiveSupport::SecureRandom.
0
+  # It is currently a wrapper around ActiveSupport::SecureRandom.
0
   class SecretKeyGenerator
0
-    GENERATORS = [ :secure_random, :win32_api, :urandom, :openssl, :prng ].freeze
0
-
0
     def initialize(identifier)
0
-      @identifier = identifier
0
     end
0
 
0
     # Generate a random secret key with the best possible method available on
0
     # the current platform.
0
     def generate_secret
0
-      generator = GENERATORS.find do |g|
0
-        self.class.send("supports_#{g}?")
0
-      end
0
-      send("generate_secret_with_#{generator}")
0
-    end
0
-
0
-    # Generate a random secret key by using the Win32 API. Raises LoadError
0
-    # if the current platform cannot make use of the Win32 API. Raises
0
-    # SystemCallError if some other error occurred.
0
-    def generate_secret_with_win32_api
0
-      # Following code is based on David Garamond's GUID library for Ruby.
0
-      require 'Win32API'
0
-
0
-      crypt_acquire_context = Win32API.new("advapi32", "CryptAcquireContext",
0
-                                           'PPPII', 'L')
0
-      crypt_gen_random = Win32API.new("advapi32", "CryptGenRandom",
0
-                                      'LIP', 'L')
0
-      crypt_release_context = Win32API.new("advapi32", "CryptReleaseContext",
0
-                                         'LI', 'L')
0
-      prov_rsa_full       = 1
0
-      crypt_verifycontext = 0xF0000000
0
-
0
-      hProvStr = " " * 4
0
-      if crypt_acquire_context.call(hProvStr, nil, nil, prov_rsa_full,
0
-                                    crypt_verifycontext) == 0
0
-        raise SystemCallError, "CryptAcquireContext failed: #{lastWin32ErrorMessage}"
0
-      end
0
-      hProv, = hProvStr.unpack('L')
0
-      bytes = " " * 64
0
-      if crypt_gen_random.call(hProv, bytes.size, bytes) == 0
0
-        raise SystemCallError, "CryptGenRandom failed: #{lastWin32ErrorMessage}"
0
-      end
0
-      if crypt_release_context.call(hProv, 0) == 0
0
-        raise SystemCallError, "CryptReleaseContext failed: #{lastWin32ErrorMessage}"
0
-      end
0
-      bytes.unpack("H*")[0]
0
-    end
0
-
0
-    # Generate a random secret key with Ruby 1.9's SecureRandom module.
0
-    # Raises LoadError if the current Ruby version does not support
0
-    # SecureRandom.
0
-    def generate_secret_with_secure_random
0
-      require 'securerandom'
0
-      return SecureRandom.hex(64)
0
-    end
0
-
0
-    # Generate a random secret key with OpenSSL. If OpenSSL is not
0
-    # already loaded, then this method will attempt to load it.
0
-    # LoadError will be raised if that fails.
0
-    def generate_secret_with_openssl
0
-      require 'openssl'
0
-      if !File.exist?("/dev/urandom")
0
-        # OpenSSL transparently seeds the random number generator with
0
-        # data from /dev/urandom. On platforms where that is not
0
-        # available, such as Windows, we have to provide OpenSSL with
0
-        # our own seed. Unfortunately there's no way to provide a
0
-        # secure seed without OS support, so we'll have to do with
0
-        # rand() and Time.now.usec().
0
-        OpenSSL::Random.seed(rand(0).to_s + Time.now.usec.to_s)
0
-      end
0
-      data = OpenSSL::BN.rand(2048, -1, false).to_s
0
-
0
-      if OpenSSL::OPENSSL_VERSION_NUMBER > 0x00908000
0
-        OpenSSL::Digest::SHA512.new(data).hexdigest
0
-      else
0
-        generate_secret_with_prng
0
-      end
0
+      ActiveSupport::SecureRandom.hex(64)
0
     end
0
-
0
-    # Generate a random secret key with /dev/urandom.
0
-    # Raises SystemCallError on failure.
0
-    def generate_secret_with_urandom
0
-      return File.read("/dev/urandom", 64).unpack("H*")[0]
0
-    end
0
-
0
-    # Generate a random secret key with Ruby's pseudo random number generator,
0
-    # as well as some environment information.
0
-    #
0
-    # This is the least cryptographically secure way to generate a secret key,
0
-    # and should be avoided whenever possible.
0
-    def generate_secret_with_prng
0
-      require 'digest/sha2'
0
-      sha = Digest::SHA2.new(512)
0
-      now = Time.now
0
-      sha << now.to_s
0
-      sha << String(now.usec)
0
-      sha << String(rand(0))
0
-      sha << String($$)
0
-      sha << @identifier
0
-      return sha.hexdigest
0
-    end
0
-
0
-    private
0
-      def lastWin32ErrorMessage
0
-        # Following code is based on David Garamond's GUID library for Ruby.
0
-        get_last_error = Win32API.new("kernel32", "GetLastError", '', 'L')
0
-        format_message = Win32API.new("kernel32", "FormatMessageA",
0
-                                      'LPLLPLPPPPPPPP', 'L')
0
-        format_message_ignore_inserts  = 0x00000200
0
-        format_message_from_system     = 0x00001000
0
-
0
-        code = get_last_error.call
0
-        msg = "\0" * 1024
0
-        len = format_message.call(format_message_ignore_inserts +
0
-                                  format_message_from_system, 0,
0
-                                  code, 0, msg, 1024, nil, nil,
0
-                                  nil, nil, nil, nil, nil, nil)
0
-        msg[0, len].tr("\r", '').chomp
0
-      end
0
-
0
-      def self.supports_secure_random?
0
-        begin
0
-          require 'securerandom'
0
-          true
0
-        rescue LoadError
0
-          false
0
-        end
0
-      end
0
-
0
-      def self.supports_win32_api?
0
-        return false unless RUBY_PLATFORM =~ /(:?mswin|mingw)/
0
-        begin
0
-          require 'Win32API'
0
-          true
0
-        rescue LoadError
0
-          false
0
-        end
0
-      end
0
-
0
-      def self.supports_urandom?
0
-        File.exist?('/dev/urandom')
0
-      end
0
-
0
-      def self.supports_openssl?
0
-        begin
0
-          require 'openssl'
0
-          true
0
-        rescue LoadError
0
-          false
0
-        end
0
-      end
0
-
0
-      def self.supports_prng?
0
-        true
0
-      end
0
   end
0
 end
...
3
4
5
6
7
 
8
9
 
10
11
12
...
54
55
56
57
58
 
...
3
4
5
 
 
6
7
 
8
9
10
11
...
53
54
55
 
56
57
0
@@ -3,10 +3,9 @@ task :environment do
0
   require(File.join(RAILS_ROOT, 'config', 'environment'))
0
 end
0
 
0
-require 'rails_generator/secret_key_generator'
0
-desc 'Generate a crytographically secure secret key. This is typically used to generate a secret for cookie sessions. Pass a unique identifier to the generator using ID="some unique identifier" for greater security.'
0
+desc 'Generate a crytographically secure secret key. This is typically used to generate a secret for cookie sessions.'
0
 task :secret do
0
-  puts Rails::SecretKeyGenerator.new(ENV['ID']).generate_secret
0
+  puts ActiveSupport::SecureRandom.hex(64)
0
 end
0
 
0
 require 'active_support'
0
@@ -54,4 +53,4 @@ namespace :time do
0
       puts "\n"
0
     end
0
   end
0
-end
0
\ No newline at end of file
0
+end
...
33
34
35
36
37
38
39
40
41
42
43
44
...
33
34
35
 
 
 
 
 
 
 
 
36
0
@@ -33,12 +33,4 @@ class SecretKeyGenerationTest < Test::Unit::TestCase
0
   def test_secret_key_generation
0
     assert @generator.generate_secret.length >= SECRET_KEY_MIN_LENGTH
0
   end
0
-
0
-  Rails::SecretKeyGenerator::GENERATORS.each do |generator|
0
-    if Rails::SecretKeyGenerator.send("supports_#{generator}?")
0
-      define_method("test_secret_key_generation_with_#{generator}") do
0
-        assert @generator.send("generate_secret_with_#{generator}").length >= SECRET_KEY_MIN_LENGTH
0
-      end
0
-    end
0
-  end
0
 end

Comments