ActiveRecord::Encryption
uses encryption contexts to configure the different entities used to encrypt/decrypt at a given moment in time.
By default, the library uses a default encryption context. This is the Context
that gets configured initially via config.active_record.encryption
options. Library users can define nested encryption contexts when running blocks of code.
See Context
.
Methods
- context
- current_custom_context
- protecting_encrypted_data
- reset_default_context
- with_encryption_context
- without_encryption
Instance Public methods
context()
Returns the current context. By default it will return the current context.
📝 Source code
# File activerecord/lib/active_record/encryption/contexts.rb, line 62
def context
self.current_custom_context || self.default_context
end
🔎 See on GitHub
current_custom_context()
📝 Source code
# File activerecord/lib/active_record/encryption/contexts.rb, line 66
def current_custom_context
self.custom_contexts&.last
end
🔎 See on GitHub
protecting_encrypted_data(&block)
Runs the provided block in an encryption context where:
-
Reading encrypted content will return its ciphertext.
-
Writing encrypted content will fail.
📝 Source code
# File activerecord/lib/active_record/encryption/contexts.rb, line 57
def protecting_encrypted_data(&block)
with_encryption_context encryptor: ActiveRecord::Encryption::EncryptingOnlyEncryptor.new, frozen_encryption: true, &block
end
🔎 See on GitHub
reset_default_context()
📝 Source code
# File activerecord/lib/active_record/encryption/contexts.rb, line 70
def reset_default_context
self.default_context = Context.new
end
🔎 See on GitHub
with_encryption_context(properties)
Configures a custom encryption context to use when running the provided block of code.
It supports overriding all the properties defined in Context
.
Example:
ActiveRecord::Encryption.with_encryption_context(encryptor: ActiveRecord::Encryption::NullEncryptor.new) do
...
end
Encryption
contexts can be nested.
📝 Source code
# File activerecord/lib/active_record/encryption/contexts.rb, line 33
def with_encryption_context(properties)
self.custom_contexts ||= []
self.custom_contexts << default_context.dup
properties.each do |key, value|
self.current_custom_context.send("#{key}=", value)
end
yield
ensure
self.custom_contexts.pop
end
🔎 See on GitHub
without_encryption(&block)
Runs the provided block in an encryption context where encryption is disabled:
-
Reading encrypted content will return its ciphertexts.
-
Writing encrypted content will write its clear text.
📝 Source code
# File activerecord/lib/active_record/encryption/contexts.rb, line 49
def without_encryption(&block)
with_encryption_context encryptor: ActiveRecord::Encryption::NullEncryptor.new, &block
end
🔎 See on GitHub