Search code examples
ruby-on-railsrubyruby-on-rails-5activesupport

Decrypting Rails 5 session manually when secret_key_base is nil?


I'm following several other SO threads on how to manually decrypt a session string...

cookie        = CGI::unescape(params[:session])
salt          = Rails.application.config.action_dispatch.encrypted_cookie_salt
signed_salt   = Rails.application.config.action_dispatch.encrypted_signed_cookie_salt
key_generator = ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base, iterations: 1000)
secret        = key_generator.generate_key(salt)[0, ActiveSupport::MessageEncryptor.key_len]
sign_secret   = key_generator.generate_key(signed_salt)
encryptor     = ActiveSupport::MessageEncryptor.new(secret, sign_secret)

decrypted_session = encryptor.decrypt_and_verify(cookie)

The problem is, in Rails 5.2 the secret_key_base is nil, which causes that step to fail. I tried an empty '' string but that also fails.

I'm not using the new master_key method, I still chose to use secret_key_base


Solution

  • For anyone trying to get the secret key base in rails 5.2, I had the same issue and after some research I used Rails.application.secret_key_base. Here is a github code showing how decrypting is done. https://gist.github.com/inopinatus/e523f36b468f94cf6d34410b73fef15e