MessageEncryptor is a simple way to encrypt values which get stored somewhere you don’t trust.

The cipher text and initialization vector are base64 encoded and returned to you.

This can be used in situations similar to the MessageVerifier, but where you don’t want users to be able to determine the value of the payload.

Methods
Constants
OpenSSLCipherError = OpenSSL::Cipher.const_defined?(:CipherError) ? OpenSSL::Cipher::CipherError : OpenSSL::CipherError
Public Class methods
new(secret, cipher = 'aes-256-cbc')
      # File activesupport/lib/active_support/message_encryptor.rb, line 16
16:     def initialize(secret, cipher = 'aes-256-cbc')
17:       @secret = secret
18:       @cipher = cipher
19:     end
Public Instance methods
decrypt(encrypted_message)
      # File activesupport/lib/active_support/message_encryptor.rb, line 36
36:     def decrypt(encrypted_message)
37:       cipher = new_cipher
38:       encrypted_data, iv = encrypted_message.split("--").map {|v| ActiveSupport::Base64.decode64(v)}
39: 
40:       cipher.decrypt
41:       cipher.key = @secret
42:       cipher.iv  = iv
43: 
44:       decrypted_data = cipher.update(encrypted_data)
45:       decrypted_data << cipher.final
46: 
47:       Marshal.load(decrypted_data)
48:     rescue OpenSSLCipherError, TypeError
49:       raise InvalidMessage
50:     end
decrypt_and_verify(value)
      # File activesupport/lib/active_support/message_encryptor.rb, line 56
56:     def decrypt_and_verify(value)
57:       decrypt(verifier.verify(value))
58:     end
encrypt(value)
      # File activesupport/lib/active_support/message_encryptor.rb, line 21
21:     def encrypt(value)
22:       cipher = new_cipher
23:       # Rely on OpenSSL for the initialization vector
24:       iv = cipher.random_iv
25: 
26:       cipher.encrypt
27:       cipher.key = @secret
28:       cipher.iv  = iv
29: 
30:       encrypted_data = cipher.update(Marshal.dump(value))
31:       encrypted_data << cipher.final
32: 
33:       [encrypted_data, iv].map {|v| ActiveSupport::Base64.encode64s(v)}.join("--")
34:     end
encrypt_and_sign(value)
      # File activesupport/lib/active_support/message_encryptor.rb, line 52
52:     def encrypt_and_sign(value)
53:       verifier.generate(encrypt(value))
54:     end
Private Instance methods
new_cipher()
      # File activesupport/lib/active_support/message_encryptor.rb, line 63
63:       def new_cipher
64:         OpenSSL::Cipher::Cipher.new(@cipher)
65:       end
verifier()
      # File activesupport/lib/active_support/message_encryptor.rb, line 67
67:       def verifier
68:         MessageVerifier.new(@secret)
69:       end