Class: Itamae::Secrets::AesKey

Inherits:
Object
  • Object
show all
Defined in:
lib/itamae/secrets/aes_key.rb

Constant Summary collapse

AES1_KEY_LEN =
OpenSSL::Cipher.new('aes-256-gcm').key_len

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type, key) ⇒ AesKey

Returns a new instance of AesKey.

Raises:

  • (ArgumentError)


37
38
39
40
41
42
# File 'lib/itamae/secrets/aes_key.rb', line 37

def initialize(name, type, key)
  raise ArgumentError, "name must not contain slashes, commas, backslackes" if name.include?("\\") || name.include?(?/) || name.include?(?:)
  @name = name
  @type = type
  @key = key
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



44
45
46
# File 'lib/itamae/secrets/aes_key.rb', line 44

def key
  @key
end

#nameObject (readonly)

Returns the value of attribute name.



44
45
46
# File 'lib/itamae/secrets/aes_key.rb', line 44

def name
  @name
end

#typeObject (readonly)

Returns the value of attribute type.



44
45
46
# File 'lib/itamae/secrets/aes_key.rb', line 44

def type
  @type
end

Class Method Details

.generate_pkcs5(name, passphrase) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/itamae/secrets/aes_key.rb', line 23

def self.generate_pkcs5(name, passphrase)
  key_len = key_len_for_type('aes1')

  salt = OpenSSL::Digest::SHA256.digest(name)
  key = OpenSSL::PKCS5.pbkdf2_hmac(passphrase, salt, 30000, key_len, OpenSSL::Digest::SHA256.new)

  new name, 'aes1', key
end

.generate_random(name) ⇒ Object



18
19
20
21
# File 'lib/itamae/secrets/aes_key.rb', line 18

def self.generate_random(name)
  key_len = key_len_for_type('aes1')
  new name, 'aes1', OpenSSL::Random.random_bytes(key_len)
end

.key_len_for_type(type) ⇒ Object



9
10
11
12
13
14
15
16
# File 'lib/itamae/secrets/aes_key.rb', line 9

def self.key_len_for_type(type)
  case type
  when 'aes1'
    AES1_KEY_LEN
  else
    raise ArgumentError, "unknown type #{type.inspect}"
  end
end

.load_json(json) ⇒ Object



32
33
34
35
# File 'lib/itamae/secrets/aes_key.rb', line 32

def self.load_json(json)
  data = JSON.parse(json)
  new(data['name'], data['type'], data['key'].unpack('m*')[0])
end

Instance Method Details

#algorithm_compatible?(algorithm) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/itamae/secrets/aes_key.rb', line 46

def algorithm_compatible?(algorithm)
  algorithm == 'aes-256-gcm'
end

#to_jsonObject



54
55
56
57
58
59
60
# File 'lib/itamae/secrets/aes_key.rb', line 54

def to_json
  {
    name: name,
    type: type,
    key: [key].pack('m*'),
  }.to_json
end

#to_sObject



50
51
52
# File 'lib/itamae/secrets/aes_key.rb', line 50

def to_s
  key
end