Class: Vagrant::Util::Keypair::Rsa

Inherits:
Object
  • Object
show all
Extended by:
Retryable
Defined in:
lib/vagrant/util/keypair.rb

Constant Summary collapse

KEY_TYPE =

Key type identifier

"ssh-rsa"

Class Method Summary collapse

Methods included from Retryable

retryable

Class Method Details

.create(password = nil) ⇒ Array<String, String, String>

Creates an SSH keypair and returns it.

Parameters:

  • password (String) (defaults to: nil)

    Password for the key, or nil for no password.

Returns:

  • (Array<String, String, String>)

    PEM-encoded public and private key, respectively. The final element is the OpenSSH encoded public key.



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/vagrant/util/keypair.rb', line 135

def self.create(password=nil)
  # This sometimes fails with RSAError. It is inconsistent and strangely
  # sleeps seem to fix it. We just retry this a few times. See GH-5056
  rsa_key = nil
  retryable(on: OpenSSL::PKey::RSAError, sleep: 2, tries: 5) do
    rsa_key = OpenSSL::PKey::RSA.new(2048)
  end

  public_key  = rsa_key.public_key
  private_key = rsa_key.to_pem

  if password
    cipher      = OpenSSL::Cipher.new('des3')
    private_key = rsa_key.to_pem(cipher, password)
  end

  # Generate the binary necessary for the OpenSSH public key.
  binary = [7].pack("N")
  binary += "ssh-rsa"
  ["e", "n"].each do |m|
    val  = public_key.send(m)
    data = val.to_s(2)

    first_byte = data[0,1].unpack("c").first
    if val < 0
      data[0] = [0x80 & first_byte].pack("c")
    elsif first_byte < 0
      data = 0.chr + data
    end

    binary += [data.length].pack("N") + data
  end

  openssh_key = "ssh-rsa #{Base64.encode64(binary).gsub("\n", "")} vagrant"
  public_key  = public_key.to_pem
  return [public_key, private_key, openssh_key]
end