跳到內容 跳到搜尋

ActiveRecord::Encryption 使用加密內容來設定不同的實體,用於在特定時間點進行加密/解密。

預設情況下,函式庫會使用預設加密內容。這是在 config.active_record.encryption 選項中透過 Context 最初設定的內容。函式庫使用者可以在執行程式區塊時定義巢狀加密內容。

請參閱 Context

方法
C
P
R
W

執行個體公開方法

context()

傳回目前的內容。預設情況下,它會傳回目前的內容。

# File activerecord/lib/active_record/encryption/contexts.rb, line 62
def context
  self.current_custom_context || self.default_context
end

current_custom_context()

# File activerecord/lib/active_record/encryption/contexts.rb, line 66
def current_custom_context
  self.custom_contexts&.last
end

protecting_encrypted_data(&block)

在加密內容中執行提供的區塊,其中

  • 讀取加密內容會傳回其密文。

  • 寫入加密內容會失敗。

# 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

reset_default_context()

# File activerecord/lib/active_record/encryption/contexts.rb, line 70
def reset_default_context
  self.default_context = Context.new
end

with_encryption_context(properties)

設定自訂加密內容,以便在執行提供的程式區塊時使用。

它支援覆寫 Context 中定義的所有屬性。

範例

ActiveRecord::Encryption.with_encryption_context(encryptor: ActiveRecord::Encryption::NullEncryptor.new) do
  ...
end

Encryption 內容可以巢狀。

# 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

without_encryption(&block)

在加密內容中執行提供的區塊,其中啟用加密

  • 讀取加密內容會傳回其密文。

  • 寫入加密內容會寫入明文。

# File activerecord/lib/active_record/encryption/contexts.rb, line 49
def without_encryption(&block)
  with_encryption_context encryptor: ActiveRecord::Encryption::NullEncryptor.new, &block
end