Class: CredStash::CipherKey

Inherits:
Object
  • Object
show all
Defined in:
lib/cred_stash/cipher_key.rb

Constant Summary collapse

DEFAULT_KMS_KEY_ID =
"alias/credstash".freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data_key:, hmac_key:, wrapped_key:) ⇒ CipherKey

Returns a new instance of CipherKey.



29
30
31
32
33
# File 'lib/cred_stash/cipher_key.rb', line 29

def initialize(data_key:, hmac_key:, wrapped_key:)
  @data_key = data_key
  @hmac_key = hmac_key
  @wrapped_key = wrapped_key
end

Instance Attribute Details

#data_keyObject (readonly)

Returns the value of attribute data_key.



4
5
6
# File 'lib/cred_stash/cipher_key.rb', line 4

def data_key
  @data_key
end

#hmac_keyObject (readonly)

Returns the value of attribute hmac_key.



4
5
6
# File 'lib/cred_stash/cipher_key.rb', line 4

def hmac_key
  @hmac_key
end

#wrapped_keyObject (readonly)

Returns the value of attribute wrapped_key.



4
5
6
# File 'lib/cred_stash/cipher_key.rb', line 4

def wrapped_key
  @wrapped_key
end

Class Method Details

.decrypt(wrapped_key, client: Aws::KMS::Client.new, context: {}) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/cred_stash/cipher_key.rb', line 20

def self.decrypt(wrapped_key, client: Aws::KMS::Client.new, context: {})
  res = client.decrypt(ciphertext_blob: wrapped_key, encryption_context: context)
  new(
    data_key: res.plaintext[0...32],
    hmac_key: res.plaintext[32..-1],
    wrapped_key: wrapped_key
  )
end

.generate(client: Aws::KMS::Client.new, kms_key_id: nil, context: {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/cred_stash/cipher_key.rb', line 6

def self.generate(client: Aws::KMS::Client.new, kms_key_id: nil,
                  context: {})
  res = client.generate_data_key(
    key_id: kms_key_id || DEFAULT_KMS_KEY_ID,
    number_of_bytes: 64,
    encryption_context: context
  )
  new(
    data_key: res.plaintext[0...32],
    hmac_key: res.plaintext[32..-1],
    wrapped_key: res.ciphertext_blob
  )
end

Instance Method Details

#decrypt(message) ⇒ Object



43
44
45
# File 'lib/cred_stash/cipher_key.rb', line 43

def decrypt(message)
  CredStash::Cipher.new(data_key).decrypt(message)
end

#encrypt(message) ⇒ Object



39
40
41
# File 'lib/cred_stash/cipher_key.rb', line 39

def encrypt(message)
  CredStash::Cipher.new(data_key).encrypt(message)
end

#hmac(message) ⇒ Object



35
36
37
# File 'lib/cred_stash/cipher_key.rb', line 35

def hmac(message)
  OpenSSL::HMAC.hexdigest("SHA256", hmac_key, message)
end