Module: RTunnel::Crypto

Defined in:
lib/rtunnel/crypto.rb

Defined Under Namespace

Classes: Hasher, KeySet

Class Method Summary collapse

Class Method Details

.decrypt_with_key(key, encrypted_data) ⇒ Object

Decrypts data that was previously encrypted with encrypt_with_key.



45
46
47
48
49
50
51
52
53
# File 'lib/rtunnel/crypto.rb', line 45

def self.decrypt_with_key(key, encrypted_data)
  if key.kind_of? OpenSSL::PKey::RSA
    key.private_decrypt encrypted_data, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING    
  elsif key.kind_of? OpenSSL::PKey::DSA
    key.private_decrypt encrypted_data
  else
    raise 'Unsupported key type'
  end
end

.encrypt_with_key(key, data) ⇒ Object

Encrypts some data with a public key. The matching private key will be required to decrypt the data.



34
35
36
37
38
39
40
41
42
# File 'lib/rtunnel/crypto.rb', line 34

def self.encrypt_with_key(key, data)
  if key.kind_of? OpenSSL::PKey::RSA
    key.public_encrypt data, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING
  elsif key.kind_of? OpenSSL::PKey::DSA
    key.public_encrypt encrypted_data
  else
    raise 'Unsupported key type'
  end
end

.key_fingerprint(key) ⇒ Object

Computes a string that represents the key. Different keys should map out to different fingerprints.



28
29
30
# File 'lib/rtunnel/crypto.rb', line 28

def self.key_fingerprint(key)
  key.public_key.to_der
end

.load_public_keys(file_name) ⇒ Object

Loads public keys to be used by a server.



56
57
58
59
# File 'lib/rtunnel/crypto.rb', line 56

def self.load_public_keys(file_name)
  key_list = read_authorized_keys file_name
  RTunnel::Crypto::KeySet.new key_list
end

.read_authorized_keys(file_name) ⇒ Object

Reads all the keys from an openssh known_hosts or authorized_keys2 file.



10
11
12
13
14
15
16
17
18
19
# File 'lib/rtunnel/crypto.rb', line 10

def self.read_authorized_keys(file_name)
  keys = []
  File.read(file_name).each_line do |line|
    pubkey_match = /ssh-\w*\s*(\S*)/.match line
    next unless pubkey_match
    pubkey_blob = pubkey_match[1].unpack('m*').first      
    keys << Net::SSH::Buffer.new(pubkey_blob).read_key
  end
  keys
end

.read_private_key(file_name) ⇒ Object

Loads a private key from an openssh key file.



22
23
24
# File 'lib/rtunnel/crypto.rb', line 22

def self.read_private_key(file_name)
  Net::SSH::KeyFactory.load_private_key file_name
end