class CookieDecryptor::Decryptor

Decrypts a Rails cookie, using ActiveSupport::KeyGenerator and ActiveSupport::MessageVerifier. If this code is running inside a Rails app, it will use the key generator and secrets the Rails app is using. Otherwise, you must pass in your app's secret_key_base, and we will use hardcoded key strings from Rails.

Public Class Methods

new(cookie, secret_key_base: nil) click to toggle source
# File lib/cookie_decryptor/decryptor.rb, line 13
def initialize(cookie, secret_key_base: nil)
  @cookie = CGI.unescape(extract_cookie(cookie))
  @key_generator = key_generator(secret_key_base)
end

Public Instance Methods

decrypt() click to toggle source

Returns the decrypted data inside cookie.

# File lib/cookie_decryptor/decryptor.rb, line 19
def decrypt
  encryptor.decrypt_and_verify(@cookie)
end

Private Instance Methods

encryptor() click to toggle source
# File lib/cookie_decryptor/decryptor.rb, line 41
def encryptor
  secret = @key_generator.generate_key("encrypted cookie")[0, ActiveSupport::MessageEncryptor.key_len]
  sign_secret = @key_generator.generate_key("signed encrypted cookie")
  ActiveSupport::MessageEncryptor.new(
    secret,
    sign_secret,
    serializer: ActiveSupport::MessageEncryptor::NullSerializer
  )
end
key_generator(secret_key_base) click to toggle source
# File lib/cookie_decryptor/decryptor.rb, line 31
def key_generator(secret_key_base)
  if secret_key_base
    ActiveSupport::KeyGenerator.new(secret_key_base, iterations: 1000)
  elsif defined?(Rails.application)
    Rails.application.key_generator
  else
    raise ArgumentError, "You must specify a secret_key_base in order to decrypt sessions."
  end
end