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.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...