123456789_123456789_123456789_123456789_123456789_

Class: ActiveRecord::Encryption::Cipher

Relationships & Source Files
Namespace Children
Classes:
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Inherits: Object
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 Aes256Gcm.

Constant Summary

Class Method Summary

Instance Method Summary

Instance Method Details

#cipher_for(secret, deterministic: false) (private)

[ GitHub ]

  
# File 'activerecord/lib/active_record/encryption/cipher.rb', line 48

def cipher_for(secret, deterministic: false)
  Aes256Gcm.new(secret, deterministic: deterministic)
end

#decrypt(encrypted_message, key:)

Decrypt the provided Message.

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

[ GitHub ]

  
# 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)

Encrypts the provided text and return an encrypted Message.

[ GitHub ]

  
# 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_length

[ GitHub ]

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

def iv_length
  Aes256Gcm.iv_length
end

#key_length

[ GitHub ]

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

def key_length
  Aes256Gcm.key_length
end

#try_to_decrypt_with_each(encrypted_text, keys:) (private)

[ GitHub ]

  
# File 'activerecord/lib/active_record/encryption/cipher.rb', line 40

def try_to_decrypt_with_each(encrypted_text, keys:)
  keys.each.with_index do |key, index|
    return cipher_for(key).decrypt(encrypted_text)
  rescue ActiveRecord::Encryption::Errors::Decryption
    raise if index == keys.length - 1
  end
end