Sha256: f5a94c2ba65792ecf0b2d3603118affe5ee545f9018bd7eb2da647f3c6655a55

Contents?: true

Size: 1.37 KB

Versions: 4

Compression:

Stored size: 1.37 KB

Contents

require "base64"
require "openssl"

module Vagrant
  module Util
    class Keypair
      # Creates an SSH keypair and returns it.
      #
      # @param [String] password Password for the key, or nil for no password.
      # @return [Array<String, String, String>] PEM-encoded public and private key,
      #   respectively. The final element is the OpenSSH encoded public
      #   key.
      def self.create(password=nil)
        rsa_key     = OpenSSL::PKey::RSA.new(2048)
        public_key  = rsa_key.public_key
        private_key = rsa_key.to_pem

        if password
          cipher      = OpenSSL::Cipher::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
    end
  end
end

Version data entries

4 entries across 1 versions & 1 rubygems

Version Path
vagrant-cloudstack-1.1.0 vendor/bundle/bundler/gems/vagrant-1cf2a8db4ccb/lib/vagrant/util/keypair.rb
vagrant-cloudstack-1.1.0 vendor/bundle/bundler/gems/vagrant-272fb27e0536/lib/vagrant/util/keypair.rb
vagrant-cloudstack-1.1.0 vendor/bundle/bundler/gems/vagrant-309e896975d1/lib/vagrant/util/keypair.rb
vagrant-cloudstack-1.1.0 vendor/bundle/bundler/gems/vagrant-b421af58e8b3/lib/vagrant/util/keypair.rb