Skip to content

Instantly share code, notes, and snippets.

@LeoMcA LeoMcA/decrypt.rb
Created Jan 13, 2019

Embed
What would you like to do?
decrypt rails session cookie (kinda)
require 'cgi'
require 'active_support'
require 'json'
# def verify_and_decrypt_session_cookie(cookie, secret_key_base = Rails.application.secret_key_base)
# cookie = CGI::unescape(cookie)
# # salt = 'authenticated encrypted cookie'
# salt = Rails.application.config.action_dispatch.encrypted_signed_cookie_salt
# encrypted_cookie_cipher = 'aes-256-gcm'
# serializer = ActiveSupport::MessageEncryptor::NullSerializer
#
# key_generator = ActiveSupport::KeyGenerator.new(secret_key_base, iterations: 1000)
# key_len = ActiveSupport::MessageEncryptor.key_len(encrypted_cookie_cipher)
# secret = key_generator.generate_key(salt, key_len)
# encryptor = ActiveSupport::MessageEncryptor.new(secret, cipher: encrypted_cookie_cipher, serializer: serializer)
#
# encryptor.decrypt_and_verify(cookie)
# end
def verify_and_decrypt_session_cookie(cookie, secret_key_base = Rails.application.secret_key_base)
cookie = CGI::unescape(cookie)
salt = 'encrypted cookie'
signed_salt = 'signed encrypted cookie'
key_generator = ActiveSupport::KeyGenerator.new(secret_key_base, iterations: 1000)
secret = key_generator.generate_key(salt)[0, ActiveSupport::MessageEncryptor.key_len]
sign_secret = key_generator.generate_key(signed_salt)
encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
string = encryptor.decrypt_and_verify(cookie)
encoding_options = {
:invalid => :replace, # Replace invalid byte sequences
:undef => :replace, # Replace anything not defined in ASCII
:replace => '', # Use a blank for those replacements
:universal_newline => true # Always break lines with \n
}
string = string.encode(Encoding.find('ASCII'), encoding_options)
string.gsub(/[^[:print:]]/i, '')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.