Forked from inopinatus/verify_and_decrypt_session_cookie52.rb
Last active
March 24, 2025 20:50
-
-
Save wildjcrt/6359713fa770d277927051fdeb30ebbf to your computer and use it in GitHub Desktop.
Decrypt Rails 6.0 beta session cookies
I got this to work with Rails 7.1 by just removing the line message = ActiveSupport::Messages::Metadata.verify(cookie_payload, "decrypt")
which wasn't working since ActiveSupport::Messages::Metadata.verify
no longer exists
Also wrote a port of this in Typescript for anyone interested https://gist.github.com/felipecsl/a6959e54caf2e53238306e2167e90ba2
In case anyone ever needs this, pre Rails 5.2 session cookies are decoded like this:
def self.decrypt_cookie(cookie, app_secret)
token_hashed = OpenSSL::PKCS5.pbkdf2_hmac_sha1(app_secret, "encrypted cookie", 1000, 32)
encrypted_message = Base64.decode64(cookie).split("--")[0]
decoded_cookie = Base64.strict_decode64(encrypted_message)
cipher = OpenSSL::Cipher.new("aes-256-cbc")
cipher.key = token_hashed
cipher.update(decoded_cookie)
end
Rails 5.2 introduced use_authenticated_cookie_encryption
, which changed the algorithm from aes-256-cbc
(old) to aes-256-gcm
(new). See here.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In case anyone is interested, I put together a gem that makes it easy to incorporate session cookies decryption/encryption into any Rails' project: https://github.com/bgvo/rails_session_cipher
You can read about the motivation in my blog