header image

Code Snippets

Decrypt Rails v4.2 Session Cookie

| Last updated:
require 'cgi'
require 'json'
require 'active_support'
require 'io/console'

def verify_and_decrypt_session_cookie(cookie, secret_key_base)
  cookie = CGI::unescape(cookie)
  salt = 'encrypted cookie'
  signed_salt = 'signed encrypted cookie'
  key_generator = ActiveSupport::KeyGenerator.new(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, serializer: JSON)

  encryptor.decrypt_and_verify(cookie)
end

puts "Enter cookie...\n\n"
cookie = gets.strip

puts "\nEnter secret key base...\n\n"
key = STDIN.noecho(&:gets).strip

puts "\nDecoded cookie:\n\n"
puts verify_and_decrypt_session_cookie(cookie, key)

Ensure rails v4.2 gem is installed: gem install rails -v '~> 4.2'

Copy script into new file named: decrypt_rails_cookie.rb

Run using: ruby decrypt_rails_cookie.rb