Method: Net::SSH::KeyFactory.load_data_private_key

Defined in:
lib/net/ssh/key_factory.rb

.load_data_private_key(data, passphrase = nil, ask_passphrase = true, filename = "") ⇒ Object

Loads a private key. It will correctly determine whether the file describes an RSA or DSA key, and will load it appropriately. The new key is returned. If the key itself is encrypted (requiring a passphrase to use), the user will be prompted to enter their password unless passphrase works.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/net/ssh/key_factory.rb', line 50

def load_data_private_key(data, passphrase=nil, ask_passphrase=true, filename="")
  if OpenSSL::PKey.respond_to?(:read)
    pkey_read = true
    error_class = ArgumentError
  else
    pkey_read = false
    if data.match(/-----BEGIN DSA PRIVATE KEY-----/)
      key_type = OpenSSL::PKey::DSA
      error_class = OpenSSL::PKey::DSAError
    elsif data.match(/-----BEGIN RSA PRIVATE KEY-----/)
      key_type = OpenSSL::PKey::RSA
      error_class = OpenSSL::PKey::RSAError
    elsif data.match(/-----BEGIN EC PRIVATE KEY-----/) && defined?(OpenSSL::PKey::EC)
      key_type = OpenSSL::PKey::EC
      error_class = OpenSSL::PKey::ECError
    elsif data.match(/-----BEGIN (.+) PRIVATE KEY-----/)
      raise OpenSSL::PKey::PKeyError, "not a supported key type '#{$1}'"
    else
      raise OpenSSL::PKey::PKeyError, "not a private key (#{filename})"
    end
  end

  encrypted_key = data.match(/ENCRYPTED/)
  tries = 0

  begin
    if pkey_read
      return OpenSSL::PKey.read(data, passphrase || 'invalid')
    else
      return key_type.new(data, passphrase || 'invalid')
    end
  rescue error_class
    if encrypted_key && ask_passphrase
      tries += 1
      if tries <= 3
        passphrase = prompt("Enter passphrase for #{filename}:", false)
        retry
      else
        raise
      end
    else
      raise
    end
  end
end