Skip to content

Instantly share code, notes, and snippets.

@pdfrod
Forked from profh/decode_session_cookie.rb
Last active July 4, 2024 14:20
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
@jwg2s
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 = ActiveSupport::KeyGenerator.new(key, iterations: key_iter_num)
  secret = key_generator.generate_key(salt)[0..key_size-1]
  sign_secret = key_generator.generate_key(signed_salt)

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

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