ruby-on-rails – Rails 4:如何解密rails 4 session cookie(给定会话密钥和秘密)

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails 4:如何解密rails 4 session cookie(给定会话密钥和秘密)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Rails 3中,会话cookie可以使用base64解码轻松解码,但在Rails 4中,cookie被编码和加密.

我想知道如何读取编码和加密的rails 4 cookie(假设我们知道密钥库).

谢谢,

解决方法

Rails 4使用 AES-256根据您应用的secret_token_base使用密钥加密Cookie.

以下是解密会话cookie的一般方案:

>计算你的密钥
> Base 64解码cookie值
>将解码后的cookie值拆分为“ – ”,这将产生两部分,第一部分是加密数据,第二部分是加密方案使用的初始化向量. Base 64独立地解码每个部分.
>通过对密钥和初始化向量应用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)

几个笔记:

>此代码段几乎与ActionDispatch :: Cookies middelware使用的实际_decript method implementation in ActiveSupport::MessageEncryptor相同.
>这是特定的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相关文章