Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Decrypt Rails 6.0 beta session cookies
require 'cgi'
require 'active_support'
def verify_and_decrypt_session_cookie(cookie, secret_key_base = Rails.application.secret_key_base)
config = Rails.application.config
cookie = CGI::unescape(cookie)
salt = config.action_dispatch.authenticated_encrypted_cookie_salt
encrypted_cookie_cipher = config.action_dispatch.encrypted_cookie_cipher || 'aes-256-gcm'
# serializer = ActiveSupport::MessageEncryptor::NullSerializer # use this line if you don't know your serializer
serializer = ActionDispatch::Cookies::JsonSerializer
key_generator =, iterations: 1000)
key_len = ActiveSupport::MessageEncryptor.key_len(encrypted_cookie_cipher)
secret = key_generator.generate_key(salt, key_len)
encryptor =, cipher: encrypted_cookie_cipher, serializer: serializer)
session_key = config.session_options[:key].freeze
encryptor.decrypt_and_verify(cookie, purpose: "cookie.#{session_key}")
Copy link

lisbethw1130 commented Dec 14, 2021

this helps a lot, thanks a lot 👍

Copy link

aizotov commented Dec 27, 2021

This is perfect 🙏 blessing be upon you

Copy link

LeKhoa commented Jan 12, 2022

I use this method but it shows below error when I call encryptor.decrypt_and_verify

*** ActiveSupport::MessageEncryptor::InvalidMessage Exception: ActiveSupport::MessageEncryptor::InvalidMessage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment