Skip to content

Instantly share code, notes, and snippets.

@erose
Created April 24, 2017 02:50
Show Gist options
  • Save erose/36a514bc5ac9c5f18552369265b4d449 to your computer and use it in GitHub Desktop.
Save erose/36a514bc5ac9c5f18552369265b4d449 to your computer and use it in GitHub Desktop.
Decrypt a Rails 5 session cookie
@srghma
Copy link

srghma commented Jul 30, 2019

for rails 5.1.5

secret = '9e99eb51b2273357d39c1604c5c8dec9b0d5c7e9fd6a9daefd509f05e093667b4c56f19afbeb25a54ed252ff4309accdce59fa232bf1ed50289987f6bb2d912a'
cookie = "bFVaWHorVXFTckxLNFlteGNHbUV5MG5IMGZEN21xaVBtNll1TElzdEE2bFdEZ0oySG5za2l4U2U2ME5sMXhiZmJGN2s4azdPTzN6VG12TGE1SWU2NksxWkhIVDlKczFRWGRCVk1HTkxVZjhzTzcreSs5MUFtV0dkVUd5TlJBdXJtNnlKTG9nWU9TeDE3dWsxRXI4NUpjdkpFYS9Pck1hMFoyeHN1R0M3M0w3Y29wM2gvc1UydElOUU9DSFd5S0cxWGpCWUxZeEdtUHFrUnFHTkhrYXFYQT09LS1jL0w3clRvZDhYRmpSdU5EU3VYaTRRPT0%3D--b502b23707be573062f99b066ae86dc50db55602"

require 'cgi'
require 'json'
require 'active_support'

def verify_and_decrypt_session_cookie(cookie, secret_key_base)
  cookie = CGI::unescape(cookie)
  salt = Rails.configuration.action_dispatch.encrypted_cookie_salt
  signed_salt = Rails.configuration.action_dispatch.encrypted_signed_cookie_salt
  key_generator = ActiveSupport::KeyGenerator.new(secret_key_base, iterations: 1000)
  secret = key_generator.generate_key(salt)[0, 32]
  sign_secret = key_generator.generate_key(signed_salt)
  encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: JSON)

  encryptor.decrypt_and_verify(cookie)
end

verify_and_decrypt_session_cookie(cookie, secret)

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