Skip to content

Instantly share code, notes, and snippets.

@pcarranza
Last active August 29, 2015 14:07
Show Gist options
  • Save pcarranza/a3e8b58418bbe03af518 to your computer and use it in GitHub Desktop.
Save pcarranza/a3e8b58418bbe03af518 to your computer and use it in GitHub Desktop.
class SSHKey
attr_reader :rsa
def initialize(args={})
source_file = args.fetch(:file) { fail ArgumentError, "Filename is required" }
source = if source_file.respond_to?(:read)
source_file.read()
else
File.open(source_file) do |file|
file.read()
end
end
@rsa = load_ssh_rsa_key(source)
@rsa ||= OpenSSL::PKey.read(source)
end
private
def load_ssh_rsa_key(source)
fail "DSA is not supported" if source =~ /^ssh-dsa/
return nil unless source =~ /^ssh-rsa/
keydata = decode_key(source)
rsakey = OpenSSL::PKey::RSA.new
skip_key_type_length = parse_data(keydata.slice!(0, 4))
keydata.slice!(0, skip_key_type_length)
exponent_length = parse_data(keydata.slice!(0, 4))
rsakey.e = parse_data(keydata.slice!(0, exponent_length))
modulus_length = parse_data(keydata.slice!(0, 4))
rsakey.n = parse_data(keydata.slice!(0, modulus_length))
@rsa = rsakey
end
def decode_key(source)
base64 = source.chomp.split[1]
keydata = base64.unpack("m").first
keydata
end
def parse_data(data)
data.bytes.inject(0) do |sum, byte|
(sum << 8) + byte
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment