Skip to content

Instantly share code, notes, and snippets.

Forked from profh/decode_session_cookie.rb
Last active March 25, 2022 15:15
Show Gist options
  • Save pdfrod/9c3b6b6f9aa1dc4726a5 to your computer and use it in GitHub Desktop.
Save pdfrod/9c3b6b6f9aa1dc4726a5 to your computer and use it in GitHub Desktop.
A simple script to decode Rails 4 session cookies
Copy link

@nvanexan, did you manage to get rid of the ActiveSupport::MessageVerifier::InvalidSignature exception? I also get this exception...

Copy link

Never mind @nvanexan, just figured it out. Had secret_key_base set both in a secrets.yml and in secret_token.rb, with different values, causing the confusion...

Copy link

smoyte commented Jan 19, 2017

For some strange reason when I tried to copy the key from Chrome it was not copying anything after the -- at the end, and that was giving me the exception above. I ended up having to type the last 32 chars by hand! Then it worked.

Copy link

talyric commented Mar 30, 2017

@robvandijk Thanks for posting about "secret_key_base set both in a secrets.yml and in secret_token.rb". That was just the clue I needed to solve a problem!

Copy link

jwg2s commented Sep 19, 2018

For anyone else who stumbles upon this, here's the updated script to actually use the key_size variable:

require 'rubygems'
require 'cgi'
require 'active_support'
require 'action_controller'

def decrypt_session_cookie(cookie, key)
  cookie = CGI::unescape(cookie)

  # Default values for Rails 5 apps
  key_iter_num = 1000
  key_size     = 32
  salt         = "encrypted cookie"
  signed_salt  = "signed encrypted cookie"

  key_generator =, iterations: key_iter_num)
  secret = key_generator.generate_key(salt)[0..key_size-1]
  sign_secret = key_generator.generate_key(signed_salt)

  encryptor =, sign_secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
  puts encryptor.decrypt_and_verify(cookie)

cookie = 'WUtLMGhlSlovNjh0ZG83OThCdzdUZDFETEhRSEUrU2cwQlB0K1JZNTNUVkRGMUs3ZUw0UmdNL3dvUnZNNzA2RmVxbk96Y0lJUTh1WnJHNE1nbnk1OCtuNEFQeTN4M0Y5OGlobkVXWTFzfaopef9RVTV1UnM4eTRIV09VQ1Y3RzNLT0pWd2hZQ3JnQnlRNHhUckRlakxlNkozQmZNbWNnYnZ3enA1b1Y0RjB4YnJyVEdMWkFOUGxiVEdmSkdsZ3NDOU84MnpZdE5LdFZRdkM1NVBjZWxmZURXY2lpTmFoMXJ6TnJzSk44NkFWcm9vdE0rV213YmMwbDVKWldrVldPbFl3V2ovS3BSRFRkaDc5TllXc0lKZVNmQ3c9PS0tT1ZCWXVoNzVreUJMWUZIdkp3QW5iQT09--fc7bfe14e7cc19c625b416e8e4bde934959bd791'
key = Rails.application.secrets.secret_key_base

decrypt_session_cookie(cookie, key)

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