我想知道如何读取编码和加密的rails 4 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.