require 'active_support/message_encryptor' require 'active_support/message_verifier' require 'active_support/key_generator' module Vinz class Crypto def initialize(key) _key = ActiveSupport::KeyGenerator.new(key).generate_key(key, 32) @crypt = ActiveSupport::MessageEncryptor.new(_key) end def encrypt(message) @crypt.encrypt_and_sign(message) end def decrypt(message) @crypt.decrypt_and_verify(message) rescue ActiveSupport::MessageVerifier::InvalidSignature => ignore raise Vinz::Error.new('invalid signature') rescue ActiveSupport::MessageEncryptor::InvalidMessage => ignore raise Vinz::Error.new('invalid message') end def encode(message) encrypted = encrypt(message) Base64.urlsafe_encode64(encrypted) end def decode(message) decoded64 = Base64.urlsafe_decode64(message) decrypt(decoded64) rescue ArgumentError => ignore raise Vinz::Error.new('invalid encoding') rescue NoMethodError => ignore raise Vinz::Error.new('invalid message') end end end