Skip to content

Instantly share code, notes, and snippets.

@technion
Last active September 2, 2017 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save technion/5cb2c6fbc570f6c1bc66e30bfb072cdf to your computer and use it in GitHub Desktop.
Save technion/5cb2c6fbc570f6c1bc66e30bfb072cdf to your computer and use it in GitHub Desktop.
module ApplicationHelper
# Use a hash so there's a bit of work to serialize
DATA = [data: 'a secret cookie', second: 'another string']
N = 100000
def storebench
# Setup keying. Really, secret and sign_secret should just get saved.
key_generator = ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base, iterations: 1000)
secret = key_generator.generate_key('encrypted cookie')
sign_secret = key_generator.generate_key('signed encrypted cookie')
#Demo cookiestore
crypt = ActiveSupport::MessageEncryptor.new(secret[0, 32], sign_secret) #, serializer: JSON)
puts crypt.inspect # Show all settings - confirm it's using JSON
# Bad function name - it doesn't really sign
encrypted_data = crypt.encrypt_and_sign(DATA)
puts "Cookiestore data is: #{encrypted_data} which is #{encrypted_data.length.to_s} in length"
#Demo libsodium
box = RbNaCl::SimpleBox.from_secret_key(secret[0, 32])
encrypted_data2 = Base64.strict_encode64(box.encrypt(DATA.to_json))
puts "Sodium data is: #{encrypted_data2} which is #{encrypted_data2.length.to_s} in length"
#Benchmark
Benchmark.bm(32) do |x|
x.report("to_json") { N.times do; DATA.to_json; end }
x.report("JSON.dump") { N.times do; JSON.dump(DATA); end }
x.report("cookiestore encrypt and sign") { N.times do; crypt.encrypt_and_sign(DATA); end }
x.report("cookiestore decrypt and verify") { N.times do; crypt.decrypt_and_verify(encrypted_data); end }
x.report("libsodium encrypt and sign") { N.times do; Base64.strict_encode64(box.encrypt(JSON.dump(DATA))); end }
x.report("libsodium decrypt") { N.times do; JSON.parse(box.decrypt(Base64.decode64(encrypted_data2))); end }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment