Skip to content

Instantly share code, notes, and snippets.

@zmajstor
Created September 14, 2014 14:47
Show Gist options
  • Save zmajstor/b841ca5ef7b9247b8b4c to your computer and use it in GitHub Desktop.
Save zmajstor/b841ca5ef7b9247b8b4c to your computer and use it in GitHub Desktop.
ActiveSupport MessageVerifier and MessageEncryptor samples
require 'active_support'
require 'active_support/key_generator'
# KeyGenerator is part of Rails since v4.0.0
# https://github.com/rails/docrails/blob/master/activesupport/lib/active_support/key_generator.rb
salt = SecureRandom.random_bytes(64)
key = ActiveSupport::KeyGenerator.new('password1234').generate_key(salt)
encryptor = ActiveSupport::MessageEncryptor.new(key)
message = "Secret message in plain text"
# Alice encrypts and sign the message...
# sign the message in order to avoid padding attacks. Reference: www.limited-entropy.com/padding-oracle-attacks.
encrypted_message = encryptor.encrypt_and_sign(message)
# # othe other side, Bob decrypts it and verify
# decrypted_message = encryptor.decrypt_and_verify(encrypted_message)
# puts "decrypted message (same as original): '#{decrypted_message}'" if decrypted_message == message
puts ""
puts "let's try to decrypt with other decryptor (other password)"
other_salt = SecureRandom.random_bytes(64)
other_key = ActiveSupport::KeyGenerator.new('password1234').generate_key(other_salt)
other_encryptor = ActiveSupport::MessageEncryptor.new(other_key)
begin
other_encryptor.decrypt_and_verify(encrypted_message)
rescue ActiveSupport::MessageVerifier::InvalidSignature
puts "message tampering detected in #decrypt_and_verify"
end
require 'active_support/message_verifier'
verifier = ActiveSupport::MessageVerifier.new('your-secret')
# Bob create and sign message
message = "String that is prevented from tampering (not encrypted)"
signed_message = verifier.generate(message)
puts signed_message
# on the otherside, Alice verifies signed message
verified_message = verifier.verify(signed_message)
puts "signed message is authentic: '#{verified_message}" if verified_message
puts ""
puts "in case of message tampering"
tampered_message = "String that is tampered"
begin
verifier.verify(tampered_message)
rescue ActiveSupport::MessageVerifier::InvalidSignature
puts "message tampering detected for '#{tampered_message}'"
end
# related blog post:
# http://monkeyandcrow.com/blog/reading_rails_how_does_message_verifier_work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment