Class: Hiera::Backend::Eyaml::Encryptors::SecretBox

Inherits:
Encryptor
  • Object
show all
Defined in:
lib/hiera/backend/eyaml/encryptors/secretbox.rb

Constant Summary collapse

VERSION =
"0.4.0"

Class Method Summary collapse

Class Method Details

.create_keysObject

Raises:

  • (StandardError)


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/hiera/backend/eyaml/encryptors/secretbox.rb', line 54

def self.create_keys
  public_key = self.option :public_key
  private_key = self.option :private_key
  raise StandardError, 'secretbox_public_key is not defined' unless public_key
  raise StandardError, 'secretbox_private_key is not defined' unless private_key

  key = RbNaCl::PrivateKey.generate
  key_b64 = Base64.encode64 key.to_bytes
  pub = key.public_key
  pub_b64 = Base64.encode64 pub.to_bytes

  EncryptHelper.ensure_key_dir_exists private_key
  EncryptHelper.write_important_file :filename => private_key, :content => key_b64, :mode => 0600
  EncryptHelper.ensure_key_dir_exists public_key
  EncryptHelper.write_important_file :filename => public_key, :content => pub_b64, :mode => 0644
  LoggingHelper.info 'Keys created OK'

end

.decrypt(message) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/hiera/backend/eyaml/encryptors/secretbox.rb', line 39

def self.decrypt message
  public_key_bin = message.byteslice(0, RbNaCl::PublicKey::BYTES)
  ciphertext = message.byteslice(RbNaCl::PublicKey::BYTES, message.length)

  # Receivers private key
  key = RbNaCl::PrivateKey.new(private_key)

  # Senders public key
  pub = RbNaCl::PublicKey.new(public_key_bin)

  # Decrypted cipher text
  box = RbNaCl::SimpleBox.from_keypair(pub, key)
  box.decrypt(ciphertext)
end

.encrypt(plaintext) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/hiera/backend/eyaml/encryptors/secretbox.rb', line 27

def self.encrypt plaintext
  # Receivers public key
  pub = RbNaCl::PublicKey.new(public_key)

  # Senders private key
  key = RbNaCl::PrivateKey.generate
  box = RbNaCl::SimpleBox.from_keypair(pub, key)

  # Public key plus cipher text
  key.public_key.to_str + box.encrypt(plaintext)
end