Skip to content

Instantly share code, notes, and snippets.

Last active June 23, 2021 13:25
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save profh/e36e5dd0bec124fef04c to your computer and use it in GitHub Desktop.
Save profh/e36e5dd0bec124fef04c to your computer and use it in GitHub Desktop.
A simple script to decode Rails 4 session cookies
Copy link

I'm getting ActiveSupport::MessageVerifier::InvalidSignature exception.
What can be the reason?

Copy link

pdfrod commented Aug 26, 2015

Until a few days ago it was working fine for me, but today I also started to get that exception. It might have been related to a Rails upgrade we did recently (we're now using 4.2.3).

Eventually I figured what changes were needed to make the script work again, and the result is here

Copy link

I was trying this with Rails 5.0.2 and I needed to trim the secret to be 32 bytes (
secret = key_generator.generate_key(salt)[0, 32]

Copy link

The example cookie and key works fine, but my development cookie and key doesn't work properly (cause ActiveSupport::MessageVerifier::InvalidSignature or ActiveSupport::MessageVerifier::InvalidMessage).

My cookie separates into two like the following.

Cookie: _session_id=ImVhOWYwNzRhNzE0NmNkNTY3MTllNTk1NDYwOGQxNjA0Ig%3D%3D--7ea05fd744c8920020f6b4ee1580f3b9a3a8f8c6; _testapp_session=ZEZkOFhjSEhZT0FqZW52aFhUaE01eE5aY21jSU5XbVhhWTdtT0NqdkhZQ0lBWElsSC9KNEsrZFFQK0ZBczB0UmpiaWlSbnBycDFDRzFDWklPWFlJYmlOR0xaS1JuNk9uM29OUHlCOHpSa0VYckkyRmtQeFFpVE5MdVBtUFdIc29Ed0ExcE5mcEl6d2RKK3Qzb2tpSTJjaS9GZGh6bStvb0pqM3UxRmVCdFJoQ3N2alBTTWVYSHkxTDZVVjZ1bmZDcXA1OE53SURGbzJnaDNlWlVLdjBBbnN2eUlPcS8rT1N3WTRldkJaSkE2YmxGT1htTC9rVkVYbWZqWW1NcENvS1gvT2M3eVRlVklOWlpOZzJ0Q1dHb3c9PS0tNXI3bUpwSE1pK3lwdlIzQ2dhN3hjdz09--8eeb9117481adeb1d307a42bef8e81e6f3da0790

How do I decrypt this cookie?

Copy link

tiwi commented Feb 12, 2020

I mocked Rails behavior from ActionDispatch::Cookies:

env = {
  "action_dispatch.signed_cookie_salt" => Rails.application.config.action_dispatch.signed_cookie_salt,
  "action_dispatch.encrypted_cookie_salt" => Rails.application.config.action_dispatch.encrypted_cookie_salt,
  "action_dispatch.encrypted_signed_cookie_salt" => Rails.application.config.action_dispatch.encrypted_signed_cookie_salt,
  "action_dispatch.secret_key_base" => Rails.application.secrets.secret_key_base,
  "action_dispatch.cookies_serializer" => Rails.application.config.action_dispatch.cookies_serializer,
  "action_dispatch.key_generator" => Rails.application.key_generator
mock_request =
mock_request.env = env
mock_request.cookies = cookies # should be a hash
jar =
app_cookies_key = Rails.application.config.session_options[:key]

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