Module: OpenSSL::PKey

Defined in:
lib/openssl/pkey.rb,
lib/openssl/pkey/ec.rb,
lib/openssl/pkey/rsa.rb

Defined Under Namespace

Classes: EC, RSA

Constant Summary collapse

SSH_CURVE_NAME_MAP =
{
  "nistp256" => "prime256v1",
  "nistp384" => "secp384r1",
  "nistp521" => "secp521r1",
}

Class Method Summary collapse

Class Method Details

.from_ssh_key(s) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/openssl/pkey.rb', line 11

def self.from_ssh_key(s)
  if s =~ /\Assh-[a-z0-9-]+ /
    # WHOOP WHOOP prefixed key detected.
    s = s.split(" ")[1]
  else
    # Discard any comment, etc that might be lurking around
    s = s.split(" ")[0]
  end

  unless s =~ /\A[A-Za-z0-9\/+]+={0,2}\z/
    raise OpenSSL::PKey::PKeyError,
          "Invalid key encoding (not valid base64)"
  end

  parts = ssh_key_lv_decode(s)

  case parts.first
  when "ssh-rsa"
    OpenSSL::PKey::RSA.new.tap do |k|
      k.e = ssh_key_mpi_decode(parts[1])
      k.n = ssh_key_mpi_decode(parts[2])
    end
  when "ssh-dss"
    OpenSSL::PKey::DSA.new.tap do |k|
      k.p = ssh_key_mpi_decode(parts[1])
      k.q = ssh_key_mpi_decode(parts[2])
      k.g = ssh_key_mpi_decode(parts[3])
    end
  when /ecdsa-sha2-/
    begin
      OpenSSL::PKey::EC.new(SSH_CURVE_NAME_MAP[parts[1]]).tap do |k|
        k.public_key = OpenSSL::PKey::EC::Point.new(k.group, parts[2])
      end
    rescue TypeError
      raise OpenSSL::PKey::PKeyError.new,
            "Unknown curve identifier #{parts[1]}"
    end
  else
    raise OpenSSL::PKey::PKeyError,
          "Unknown key type #{parts.first.inspect}"
  end
end