Class: Teak::AttrEncrypted::KEKProvider::AES

Inherits:
Base
  • Object
show all
Defined in:
lib/teak/attr_encrypted/kek_provider/aes.rb

Overview

Provides a random key encrypted with a given aes-256-gcm key NOTE: This uses a random iv and is only considered secure for 2**32 invocations of request_data_key.

Defined Under Namespace

Classes: Decrypted, KeyInfo

Constant Summary collapse

CIPHER =
'aes-256-gcm'

Instance Attribute Summary

Attributes inherited from Base

#id

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ AES

Returns a new instance of AES.



20
21
22
23
# File 'lib/teak/attr_encrypted/kek_provider/aes.rb', line 20

def initialize(key)
  super(OpenSSL::Digest::SHA256.hexdigest(key))
  @key = key
end

Instance Method Details

#decrypt_data_key(ciphertext_blob, encryption_context) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/teak/attr_encrypted/kek_provider/aes.rb', line 42

def decrypt_data_key(ciphertext_blob, encryption_context)
  data = MessagePack.unpack(ciphertext_blob)
  cipher = OpenSSL::Cipher.new(CIPHER).decrypt
  cipher.key = @key
  cipher.iv = data['iv']
  cipher.auth_tag = data['tag']
  cipher.auth_data =
    if encryption_context
      MessagePack.pack(encryption_context)
    else
      ''
    end

  data_key = cipher.update(data['key']) + cipher.final
  Decrypted.new(data_key)
end

#request_data_key(encryption_context) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/teak/attr_encrypted/kek_provider/aes.rb', line 25

def request_data_key(encryption_context)
  data_key = OpenSSL::Cipher.new(CIPHER).encrypt.random_key
  cipher = OpenSSL::Cipher.new(CIPHER).encrypt
  cipher.key = @key
  iv = cipher.random_iv
  cipher.auth_data =
    if encryption_context
      MessagePack.pack(encryption_context)
    else
      ''
    end
  ciphertext = cipher.update(data_key) + cipher.final
  ciphertext_blob = MessagePack.pack({'iv' => iv, 'tag' => cipher.auth_tag, 'key' => ciphertext})

  KeyInfo.new(data_key, ciphertext_blob)
end