4
# MessageEncryptor is a simple way to encrypt values which get stored somewhere
7
# The cipher text and initialization vector are base64 encoded and returned to you.
9
# This can be used in situations similar to the MessageVerifier, but where you don't
10
# want users to be able to determine the value of the payload.
11
class MessageEncryptor
12
class InvalidMessage < StandardError; end
13
OpenSSLCipherError = OpenSSL::Cipher.const_defined?(:CipherError) ? OpenSSL::Cipher::CipherError : OpenSSL::CipherError
15
def initialize(secret, cipher = 'aes-256-cbc')
22
# Rely on OpenSSL for the initialization vector
29
encrypted_data = cipher.update(Marshal.dump(value))
30
encrypted_data << cipher.final
32
[encrypted_data, iv].map {|v| ActiveSupport::Base64.encode64s(v)}.join("--")
35
def decrypt(encrypted_message)
37
encrypted_data, iv = encrypted_message.split("--").map {|v| ActiveSupport::Base64.decode64(v)}
43
decrypted_data = cipher.update(encrypted_data)
44
decrypted_data << cipher.final
46
Marshal.load(decrypted_data)
47
rescue OpenSSLCipherError, TypeError
51
def encrypt_and_sign(value)
52
verifier.generate(encrypt(value))
55
def decrypt_and_verify(value)
56
decrypt(verifier.verify(value))
63
OpenSSL::Cipher::Cipher.new(@cipher)
67
MessageVerifier.new(@secret)