Permalink
Browse files

Cache generated keys per KeyGenerator instance using salt + key_size

  • Loading branch information...
1 parent 47da574 commit 851e8fe897633f095a0f39a91f8bc75eee7a76aa @spastorino spastorino committed Nov 1, 2012
Showing with 22 additions and 5 deletions.
  1. +14 −0 activesupport/lib/active_support/key_generator.rb
  2. +8 −5 railties/lib/rails/application.rb
@@ -1,3 +1,4 @@
+require 'mutex_m'
require 'openssl'
module ActiveSupport
@@ -21,6 +22,19 @@ def generate_key(salt, key_size=64)
end
end
+ class CachingKeyGenerator
+ def initialize(key_generator)
+ @key_generator = key_generator
+ @cache_keys = {}.extend(Mutex_m)
+ end
+
+ def generate_key(salt, key_size=64)
+ @cache_keys.synchronize do
+ @cache_keys["#{salt}#{key_size}"] ||= @key_generator.generate_key(salt, key_size)
+ end
+ end
+ end
+
class DummyKeyGenerator
def initialize(secret)
@secret = secret
@@ -108,11 +108,14 @@ def reload_routes!
def key_generator
# number of iterations selected based on consultation with the google security
# team. Details at https://github.com/rails/rails/pull/6952#issuecomment-7661220
- @key_generator ||= if config.secret_token_key
- ActiveSupport::KeyGenerator.new(config.secret_token_key, iterations: 1000)
- else
- ActiveSupport::DummyKeyGenerator.new(config.secret_token)
- end
+ @caching_key_generator ||= begin
+ if config.secret_token_key
+ key_generator = ActiveSupport::KeyGenerator.new(config.secret_token_key, iterations: 1000)
+ ActiveSupport::CachingKeyGenerator.new(key_generator)
+ else
+ ActiveSupport::DummyKeyGenerator.new(config.secret_token)
+ end
+ end
end
# Stores some of the Rails initial environment parameters which

0 comments on commit 851e8fe

Please sign in to comment.