Last active
August 29, 2015 14:10
-
-
Save selvan/599347dbe7b418b83f0b to your computer and use it in GitHub Desktop.
Session Encryption Rails
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
module MyAppEncryptor | |
app = Rails.application | |
config = app.config | |
# PBKDF2 with SHA-1 | |
key_generator = ActiveSupport::KeyGenerator.new(app.secrets[:secret_key_base], iterations: 1000) | |
secret = key_generator.generate_key(config.action_dispatch.encrypted_cookie_salt) | |
sign_secret = key_generator.generate_key(config.action_dispatch.encrypted_signed_cookie_salt) | |
@encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret) | |
def self.encrypt_and_sign(msg_to_encrypt) | |
CGI.escape(Base64.encode64(@encryptor.encrypt_and_sign(msg_to_encrypt))) | |
end | |
def self.decrypt_and_verify(encrypted_msg) | |
@encryptor.decrypt_and_verify(Base64.decode64(CGI.unescape(encrypted_msg))) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment