Last active
December 29, 2015 16:28
-
-
Save mattetti/7697301 to your computer and use it in GitHub Desktop.
Quick high level rundown showing how Rails 4 sets the message encryptor used for sessions, signed messages and more.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "active_support" | |
require "active_support/key_generator" | |
require "json" | |
# Based on https://gist.github.com/mattetti/7624413 | |
module JsonSessionSerializer | |
def self.load(value) | |
begin | |
JSON.parse(value) | |
rescue JSON::ParserError | |
nil | |
end | |
end | |
def self.dump(value) | |
JSON.generate(value) | |
end | |
end | |
options = { | |
signed_cookie_salt: "signed cookie", | |
encrypted_cookie_salt: "encrypted cookie", | |
encrypted_signed_cookie_salt: "signed encrypted cookie", | |
secret_key_base: | |
"f7b5763636f4c1f3ff4bd444eacccca295d87b990cc104124017ad70550edcfd22b8e89465338254e0b608592a9aac29025440bfd9ce53579835ba06a86f85f9" | |
} | |
# JSON serialized cookie | |
cookie_content = "TDZIdC9GcEVRSnR0aFlqYTI1SmRWTmw3NWxpRkJZNDVMK0NIUXFlcThWWitLeVQzMFVBUTE2RU82RnRsUUxQWnhyWG95dFJSRDc0OVpkVzhGWXlIb1hERHhPdk5mYStkd3pVVUZNbE1vcDRqU01MYVZJMVpMWVI5SmIweFo1N2tqWTdZcVhyWmdnc2NhZUY2b1BBMlNKWkVsT0Y0aEVQcVVKaGRISk0zR3JLWXdjaFMxamN2aThVL2hBMHBmSGx5bGg4UjUzRFErejlQVEM0eUZjcStSM3VYUkNERjBMdUVqQzZaQk5ZNHpjRT0tLUhDQ2RraWpKRDBleUp1Rm1OeVA5Snc9PQ==--61cd94a037a0a006a01403952a652ddc5da1a597" | |
# keys get cached as "#{salt}#{size}" to reuse the same derived keys. | |
key_generator = ActiveSupport::CachingKeyGenerator.new(ActiveSupport::KeyGenerator.new(options[:secret_key_base], iterations: 1000)) | |
secret = key_generator.generate_key(options[:encrypted_cookie_salt]) | |
sign_secret = key_generator.generate_key(options[:encrypted_signed_cookie_salt]) | |
encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, { serializer: JsonSessionSerializer } ) | |
#encrypted_message = encryptor.encrypt_and_sign({hello: "world"}) | |
#puts encryptor.decrypt_and_verify(encrypted_message) # => {:hello=>"world"} | |
puts encryptor.decrypt_and_verify(cookie_content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment