Class: EncryptedStore::ActiveRecord::EncryptionKey

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/encrypted_store/active_record/encryption_key.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

._create_primary_key(dek) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/encrypted_store/active_record/encryption_key.rb', line 55

def _create_primary_key(dek)
  self.new.tap { |key|
    key.dek = EncryptedStore.encrypt_key(dek, true)
    key.primary = true
    key.save!
  }
end

._has_primary?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/encrypted_store/active_record/encryption_key.rb', line 51

def _has_primary?
  where(primary: true).exists?
end

.new_key(custom_key = nil) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/encrypted_store/active_record/encryption_key.rb', line 15

def new_key(custom_key = nil)
  dek = custom_key || SecureRandom.random_bytes(32)

  transaction {
    _has_primary? && where(primary: true).first.update_attributes(primary: false)
    _create_primary_key(dek)
  }
end

.preload(amount) ⇒ Object

Preload the most recent ‘amount` keys.



41
42
43
44
# File 'lib/encrypted_store/active_record/encryption_key.rb', line 41

def preload(amount)
  primary_encryption_key # Ensure there's at least a primary key
  order('id DESC').limit(amount)
end

.primary_encryption_keyObject



10
11
12
13
# File 'lib/encrypted_store/active_record/encryption_key.rb', line 10

def primary_encryption_key
  new_key unless _has_primary?
  where(primary: true).last || last
end

.retire_keys(key_ids = []) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/encrypted_store/active_record/encryption_key.rb', line 24

def retire_keys(key_ids = [])
  pkey = primary_encryption_key

  ActiveRecord::Mixin.descendants.each { |model|
    records = key_ids.empty? ? model.where("encryption_key_id != ?", pkey.id)
                             : model.where("encryption_key_id IN (?)", key_ids)

    records.find_in_batches do |batch|
      batch.each { |record| record.reencrypt(pkey) }
    end
  }

  pkey
end

.rotate_keysObject



46
47
48
49
# File 'lib/encrypted_store/active_record/encryption_key.rb', line 46

def rotate_keys
  new_key
  retire_keys
end

Instance Method Details

#decrypted_keyObject

Class Methods



64
65
66
# File 'lib/encrypted_store/active_record/encryption_key.rb', line 64

def decrypted_key
  EncryptedStore.decrypt_key(self.dek, self.primary)
end