Class: Desviar::EncryptedItem

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

Defined Under Namespace

Modules: Decryptor, Encryptor Classes: DecryptionFailure, UnacceptableEncryptedDataBagItemFormat, UnsupportedCipher, UnsupportedEncryptedDataBagItemFormat

Constant Summary collapse

ALGORITHM =
'aes-256-cbc'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enc_hash, secret) ⇒ EncryptedItem

Returns a new instance of EncryptedItem.



353
354
355
356
# File 'lib/encrypt.rb', line 353

def initialize(enc_hash, secret)
  @enc_hash = enc_hash
  @secret = secret
end

Class Method Details

.encrypt_data_bag_item(plain_hash, secret) ⇒ Object



375
376
377
378
379
380
381
382
383
384
# File 'lib/encrypt.rb', line 375

def self.encrypt_data_bag_item(plain_hash, secret)
  plain_hash.inject({}) do |h, (key, val)|
    h[key] = if key != "id"
               Encryptor.new(val, secret).for_encrypted_item
             else
               val
             end
    h
  end
end

.load(data_bag, name, secret = nil) ⇒ Object



386
387
388
389
390
# File 'lib/encrypt.rb', line 386

def self.load(data_bag, name, secret = nil)
  raw_hash = Chef::DataBagItem.load(data_bag, name)
  secret = secret || self.load_secret
  self.new(raw_hash, secret)
end

.load_secret(path = nil) ⇒ Object



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/encrypt.rb', line 392

def self.load_secret(path=nil)
  path ||= Chef::Config[:encrypted_data_bag_secret]
  secret = case path
           when /^\w+:\/\//
             # We have a remote key
             begin
               Kernel.open(path).read.strip
             rescue Errno::ECONNREFUSED
               raise ArgumentError, "Remote key not available from '#{path}'"
             rescue OpenURI::HTTPError
               raise ArgumentError, "Remote key not found at '#{path}'"
             end
           else
             if !File.exist?(path)
               raise Errno::ENOENT, "file not found '#{path}'"
             end
             IO.read(path).strip
           end
  if secret.size < 1
    raise ArgumentError, "invalid zero length secret in '#{path}'"
  end
  secret
end

Instance Method Details

#[](key) ⇒ Object



358
359
360
361
362
363
364
365
# File 'lib/encrypt.rb', line 358

def [](key)
  value = @enc_hash[key]
  if key == "id" || value.nil?
    value
  else
    Decryptor.for(value, @secret).for_decrypted_item
  end
end

#[]=(key, value) ⇒ Object

Raises:

  • (ArgumentError)


367
368
369
# File 'lib/encrypt.rb', line 367

def []=(key, value)
  raise ArgumentError, "assignment not supported for #{self.class}"
end

#to_hashObject



371
372
373
# File 'lib/encrypt.rb', line 371

def to_hash
  @enc_hash.keys.inject({}) { |hash, key| hash[key] = self[key]; hash }
end