Last active
August 29, 2015 14:07
-
-
Save pcarranza/64f77136549ca7422574 to your computer and use it in GitHub Desktop.
Load RSA key from ssh id_rsa.pub file (timid)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def load_rsa_key(key) | |
case key | |
when nil | |
raise ArgumentError, "Key cannot be nil" | |
when OpenSSL::PKey::PKey | |
key | |
when String, File, IO | |
text = read_file(key) | |
if text =~ /^ssh-rsa/ | |
load_ssh_pubkey text | |
else | |
OpenSSL::PKey.read text | |
end | |
end | |
end | |
private | |
def load_ssh_pubkey(text) | |
rsakey = OpenSSL::PKey::RSA.new | |
text.lines.each do |line| | |
base64 = line.chomp.split[1] | |
keydata = base64.unpack("m").first | |
parts = Array.new | |
while (keydata.length > 0) | |
dlen = keydata[0, 4].bytes.inject(0) do |a, b| | |
(a << 8) + b | |
end | |
data = keydata[4, dlen] | |
keydata = keydata[(dlen + 4)..-1] | |
parts.push(data) | |
end | |
type = parts[0] | |
raise ArgumentError, "Unsupported key type #{type}" unless type == "ssh-rsa" | |
e = parts[1].bytes.inject do |a, b| | |
(a << 8) + b | |
end | |
n = parts[2].bytes.inject do |a, b| | |
(a << 8) + b | |
end | |
rsakey.n = n | |
rsakey.e = e | |
end | |
rsakey | |
end | |
def read_file file | |
f = open_file file, 'r' | |
f.read | |
end | |
def open_file file, mode | |
case file | |
when String | |
File.open file, mode | |
when File, IO | |
file | |
else | |
raise ArgumentError, "Invalid file #{file}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment