在 Rails 3 中, session cookie 可以很容易地使用 base64 解码进行解码,但在 Rails 4 中,cookie 被编码和加密。
我想知道如何读取经过编码和加密的 rails 4 cookie(假设我们知道 keystore )。
谢谢,
最佳答案
Rails 4 用途 AES-256使用基于您应用程序的 secret_token_base
的 key 加密 cookie .
这是解密 session cookie的一般方案:
我找不到可以轻松解密消息的网站(欢迎提供建议),以编程方式可以这样做:
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
使用中间件。 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/