Class: ActiveRecord::Encryption::Cipher

Inherits:
Object
  • Object
show all
Extended by:
ActiveSupport::Autoload
Defined in:
activerecord/lib/active_record/encryption/cipher.rb,
activerecord/lib/active_record/encryption.rb,
activerecord/lib/active_record/encryption/cipher/aes256_gcm.rb

Overview

The algorithm used for encrypting and decrypting Message objects.

It uses AES-256-GCM. It will generate a random IV for non deterministic encryption (default) or derive an initialization vector from the encrypted content for deterministic encryption.

See Cipher::Aes256Gcm.

Defined Under Namespace

Classes: Aes256Gcm

Constant Summary collapse

DEFAULT_ENCODING =
Encoding::UTF_8

Instance Method Summary collapse

Methods included from ActiveSupport::Autoload

autoload, autoload_at, autoload_under, eager_autoload, eager_load!, extended

Instance Method Details

#decrypt(encrypted_message, key:) ⇒ Object

Decrypt the provided Message.

When key is an Array, it will try all the keys raising a ActiveRecord::Encryption::Errors::Decryption if none works.



25
26
27
28
29
# File 'activerecord/lib/active_record/encryption/cipher.rb', line 25

def decrypt(encrypted_message, key:)
  try_to_decrypt_with_each(encrypted_message, keys: Array(key)).tap do |decrypted_text|
    decrypted_text.force_encoding(encrypted_message.headers.encoding || DEFAULT_ENCODING)
  end
end

#encrypt(clean_text, key:, deterministic: false) ⇒ Object

Encrypts the provided text and return an encrypted Message.



15
16
17
18
19
# File 'activerecord/lib/active_record/encryption/cipher.rb', line 15

def encrypt(clean_text, key:, deterministic: false)
  cipher_for(key, deterministic: deterministic).encrypt(clean_text).tap do |message|
    message.headers.encoding = clean_text.encoding.name unless clean_text.encoding == DEFAULT_ENCODING
  end
end

#iv_lengthObject



35
36
37
# File 'activerecord/lib/active_record/encryption/cipher.rb', line 35

def iv_length
  Aes256Gcm.iv_length
end

#key_lengthObject



31
32
33
# File 'activerecord/lib/active_record/encryption/cipher.rb', line 31

def key_length
  Aes256Gcm.key_length
end