W3cubDocs

/Ruby on Rails 7.0

class ActiveRecord::Encryption::Encryptor

Parent:
Object

An encryptor exposes the encryption API that ActiveRecord::Encryption::EncryptedAttributeType uses for encrypting and decrypting attribute values.

It interacts with a KeyProvider for getting the keys, and delegate to ActiveRecord::Encryption::Cipher the actual encryption algorithm.

Constants

DECRYPT_ERRORS
ENCODING_ERRORS
THRESHOLD_TO_JUSTIFY_COMPRESSION

Public Instance Methods

decrypt(encrypted_text, key_provider: default_key_provider, cipher_options: {}) Show source
# File activerecord/lib/active_record/encryption/encryptor.rb, line 52
def decrypt(encrypted_text, key_provider: default_key_provider, cipher_options: {})
  message = deserialize_message(encrypted_text)
  keys = key_provider.decryption_keys(message)
  raise Errors::Decryption unless keys.present?
  uncompress_if_needed(cipher.decrypt(message, key: keys.collect(&:secret), **cipher_options), message.headers.compressed)
rescue *(ENCODING_ERRORS + DECRYPT_ERRORS)
  raise Errors::Decryption
end

Decrypts a clean_text and returns the result as clean text

Options

:key_provider

Key provider to use for the encryption operation. It will default to ActiveRecord::Encryption.key_provider when not provided

:cipher_options

Cipher-specific options that will be passed to the Cipher configured in ActiveRecord::Encryption.cipher

encrypt(clear_text, key_provider: default_key_provider, cipher_options: {}) Show source
# File activerecord/lib/active_record/encryption/encryptor.rb, line 34
def encrypt(clear_text, key_provider: default_key_provider, cipher_options: {})
  clear_text = force_encoding_if_needed(clear_text) if cipher_options[:deterministic]

  validate_payload_type(clear_text)
  serialize_message build_encrypted_message(clear_text, key_provider: key_provider, cipher_options: cipher_options)
end

Encrypts clean_text and returns the encrypted result

Internally, it will:

  1. Create a new ActiveRecord::Encryption::Message

  2. Compress and encrypt clean_text as the message payload

  3. Serialize it with ActiveRecord::Encryption.message_serializer (ActiveRecord::Encryption::SafeMarshal by default)

  4. Encode the result with Base 64

Options

:key_provider

Key provider to use for the encryption operation. It will default to ActiveRecord::Encryption.key_provider when not provided

:cipher_options

Cipher-specific options that will be passed to the Cipher configured in ActiveRecord::Encryption.cipher

encrypted?(text) Show source
# File activerecord/lib/active_record/encryption/encryptor.rb, line 62
def encrypted?(text)
  deserialize_message(text)
  true
rescue Errors::Encoding, *DECRYPT_ERRORS
  false
end

Returns whether the text is encrypted or not

© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.