class ActiveSupport::MessageEncryptor

Overview

Encrypts and decrypts a string with an AEAD cipher, in the envelope Rails uses.

encryptor = ActiveSupport::MessageEncryptor.new("00112233445566778899aabbccddeeff".hexbytes, cipher: "aes-128-gcm")
message = encryptor.encrypt_and_sign("hello")
# => "Base64(ciphertext)--Base64(iv)--Base64(auth_tag)"
encryptor.decrypt_and_verify(message) # => "hello"

Only AEAD ciphers are supported, which is every cipher Rails pairs this class with by default: aes-256-gcm for its own messages and aes-128-gcm for ActiveSupport::EncryptedFile. An AEAD cipher authenticates its own output, so unlike Rails this class never falls back to a separate MessageVerifier signature, and a cipher without an authentication tag is rejected up front instead of being silently accepted unsigned.

The payload is a String. Rails serializes arbitrary objects here, but every file it encrypts goes through EncryptedFile, which reads and writes the contents as a string.

Ported from https://github.com/rails/rails/blob/v8.1.3/activesupport/lib/active_support/message_encryptor.rb

Defined in:

active_support/message_encryptor.cr

Constant Summary

AUTH_TAG_LENGTH = 16

Length of the GCM authentication tag Rails appends, in bytes.

DEFAULT_CIPHER = "aes-256-gcm"

The cipher Rails uses when none is given. EncryptedFile overrides it with aes-128-gcm.

SEPARATOR = "--"

Separator between the three parts of an envelope.

Constructors

Class Method Summary

Instance Method Summary

Constructor Detail

def self.new(secret : Bytes, cipher : String = DEFAULT_CIPHER, serializer : Serializer = MarshalSerializer.new) #

Builds an encryptor for secret and cipher.

secret must be exactly as long as the cipher's key. Rails only requires it to be long enough and lets OpenSSL ignore the excess, which turns a 32-byte key handed to aes-128-gcm into a silently different key. Raising keeps the two ciphers this shard deals with from being confused for one another.


Class Method Detail

def self.key_len(cipher : String = DEFAULT_CIPHER) : Int32 #

Returns the key length of cipher, in bytes: 16 for aes-128-gcm, 32 for aes-256-gcm.


Instance Method Detail

def cipher : String #

def decrypt_and_verify(message : String) : String #

Returns the value carried by message, raising InvalidMessage when it cannot be decrypted.


def decrypt_and_verify?(message : String) : String | Nil #

Returns the value carried by message, or nil when it cannot be decrypted.


def encrypt_and_sign(value : String) : String #

Returns value encrypted into a Base64(ciphertext)--Base64(iv)--Base64(auth_tag) envelope.

A fresh random IV is used on every call, so the same value never encrypts to the same envelope twice.