ruby-on-rails - rails 4 : How to decrypt rails 4 session cookie (Given the session key and secret)

标签 ruby-on-rails session ruby-on-rails-4 session-cookies

在 Rails 3 中, session cookie 可以很容易地使用 base64 解码进行解码,但在 Rails 4 中,cookie 被编码和加密。

我想知道如何读取经过编码和加密的 rails 4 cookie(假设我们知道 keystore )。

谢谢,

最佳答案

Rails 4 用途 AES-256使用基于您应用程序的 secret_token_base 的 key 加密 cookie .

这是解密 session cookie的一般方案:

  • 计算您的 key
  • Base 64 解码 cookie 值
  • 用'--'分割解码的cookie值,这将导致两部分,第一部分是加密数据,第二部分是加密方案使用的初始化向量。 Base 64 独立解码每个部分。
  • 通过使用 key 和初始化向量应用 AES 解密来解密加密数据。

  • 我找不到可以轻松解密消息的网站(欢迎提供建议),以编程方式可以这样做:
    secret = OpenSSL::PKCS5.pbkdf2_hmac_sha1(app_secret_token, 'encrypted cookie', 1000, 64)
    
    encrypted_message = Base64.decode64(cookie_str)
    cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
    encrypted_data, iv = encrypted_message.split("--").map {|v| ::Base64.strict_decode64(v)}
    
    cipher.decrypt
    cipher.key = secret
    cipher.iv  = iv
    
    decrypted_data = cipher.update(encrypted_data)
    decrypted_data << cipher.final
    
    Marshal.load(decrypted_data)
    

    几个注意事项:
  • 此代码片段与实际 _decript method implementation in ActiveSupport::MessageEncryptor 几乎相同由 ActionDispatch::Cookies 使用中间件。
  • 这完全是 Rails 4 特有的,来自 ActionDispatch::Session::CookieJar:

    If you only have secret_token set, your cookies will be signed, but not encrypted. This means a user cannot alter their +user_id+ without knowing your app's secret key, but can easily read their +user_id+. This was the default for Rails 3 apps.

    If you have secret_key_base set, your cookies will be encrypted. This goes a step further than signed cookies in that encrypted cookies cannot be altered or read by users. This is the default starting in Rails 4.

  • 关于ruby-on-rails - rails 4 : How to decrypt rails 4 session cookie (Given the session key and secret),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35013568/

    相关文章:

    ruby-on-rails - 如何将根据关系计数过滤的结果返回到 RAILS 中的 View ?

    ruby-on-rails - 使用 2 个电子邮件和凭据在 Rails 中发送电子邮件

    ruby-on-rails-4 - 如何使 `thin` 网络服务器打印日志到 STDOUT

    ruby-on-rails - Unicorn + Rails + 大型上传

    ruby-on-rails - 我应该如何在我的 Minitest 测试中为 Rails 应用程序指定要读取的文件?

    python - GAE Webapp2 - 销毁 session 不起作用

    python:与cgi脚本中的 session 交互

    ruby-on-rails - Rails Controller 检查 Turbolinks 是否请求

    ruby-on-rails - Ruby-Thin 服务器在生产中随机崩溃

    java - 如何在 Java HTTP Servlet session 结束时运行任意代码?