Module: Legion::Crypt::Cipher

Includes:
ClusterSecret
Included in:
Legion::Crypt
Defined in:
lib/legion/crypt/cipher.rb

Instance Method Summary collapse

Methods included from ClusterSecret

#cluster_secret_timeout, #cs, #find_cluster_secret, #force_cluster_secret, #from_settings, #from_transport, #from_vault, #generate_secure_random, #only_member?, #push_cs_to_vault, #secret_length, #set_cluster_secret, #settings_push_vault, #validate_hex

Instance Method Details

#decrypt(message, iv) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/legion/crypt/cipher.rb', line 17

def decrypt(message, iv)
  until cs.is_a?(String) || Legion::Settings[:client][:shutting_down]
    Legion::Logging.debug('sleeping Legion::Crypt.decrypt due to CS not being set')
    sleep(0.5)
  end

  decipher = OpenSSL::Cipher.new('aes-256-cbc')
  decipher.decrypt
  decipher.key = cs
  decipher.iv = Base64.decode64(iv)
  message = Base64.decode64(message)
  decipher.update(message) + decipher.final
end

#decrypt_from_keypair(message:, **_opts) ⇒ Object



37
38
39
# File 'lib/legion/crypt/cipher.rb', line 37

def decrypt_from_keypair(message:, **_opts)
  private_key.private_decrypt(Base64.decode64(message))
end

#encrypt(message) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/legion/crypt/cipher.rb', line 9

def encrypt(message)
  cipher = OpenSSL::Cipher.new('aes-256-cbc')
  cipher.encrypt
  cipher.key = cs
  iv = cipher.random_iv
  { enciphered_message: Base64.encode64(cipher.update(message) + cipher.final), iv: Base64.encode64(iv) }
end

#encrypt_from_keypair(message:, pub_key: public_key) ⇒ Object



31
32
33
34
35
# File 'lib/legion/crypt/cipher.rb', line 31

def encrypt_from_keypair(message:, pub_key: public_key)
  rsa_public_key = OpenSSL::PKey::RSA.new(pub_key)

  Base64.encode64(rsa_public_key.public_encrypt(message))
end

#private_keyObject



45
46
47
48
49
50
51
# File 'lib/legion/crypt/cipher.rb', line 45

def private_key
  @private_key ||= if Legion::Settings[:crypt][:read_private_key] && File.exist?('./legionio.key')
                     OpenSSL::PKey::RSA.new File.read './legionio.key'
                   else
                     OpenSSL::PKey::RSA.new 2048
                   end
end

#public_keyObject



41
42
43
# File 'lib/legion/crypt/cipher.rb', line 41

def public_key
  @public_key ||= private_key.public_key.to_s
end