Skip to content

Instantly share code, notes, and snippets.

@buncis
Created January 4, 2025 11:09
Show Gist options
  • Save buncis/16931235d110cd8aca5cdd7890e0bff9 to your computer and use it in GitHub Desktop.
Save buncis/16931235d110cd8aca5cdd7890e0bff9 to your computer and use it in GitHub Desktop.
rails session decryptor
def decrypt_cookie(cookie)
cookie = CGI.unescape(cookie)
data, iv, auth_tag = cookie.split("--").map { |v| Base64.strict_decode64(v) }
raise InvalidMessage if (auth_tag.nil? || auth_tag.bytes.length != 16)
cipher = OpenSSL::Cipher.new("aes-256-gcm")
secret = OpenSSL::PKCS5.pbkdf2_hmac(
Rails.application.secret_key_base,
Rails.configuration.action_dispatch.authenticated_encrypted_cookie_salt,
1000,
cipher.key_len,
Rails.configuration.active_support.hash_digest_class.new
)
# Setup cipher for decryption and add inputs
cipher.decrypt
cipher.key = secret
cipher.iv = iv
cipher.auth_tag = auth_tag
cipher.auth_data = ""
# Perform decryption
cookie_payload = cipher.update(data)
cookie_payload << cipher.final
cookie_payload = JSON.parse(cookie_payload)
JSON.parse(Base64.decode64(cookie_payload["_rails"]["message"]))
end
@buncis
Copy link
Author

buncis commented Jan 4, 2025

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