Skip to content

Instantly share code, notes, and snippets.

@rkh
Created July 18, 2012 11:05
Show Gist options
  • Select an option

  • Save rkh/3135592 to your computer and use it in GitHub Desktop.

Select an option

Save rkh/3135592 to your computer and use it in GitHub Desktop.
require 'base64'
def public_base64(key)
["ssh-rsa", Base64.encode64(ssh_public_key_conversion(key)).gsub("\n", "")].join(" ").strip
end
def ssh_public_key_conversion(public_key)
out = [0, 0, 0, 7].pack("C*")
out += "ssh-rsa"
["e", "n"].each do |method|
value = public_key.send(method).to_i
byte_array = to_byte_array(value)
out += encode_unsigned_int_32(byte_array.length).pack("c*")
out += byte_array.pack("C*")
end
out
end
def encode_unsigned_int_32(value)
out = []
out[0] = value >> 24 & 0xff
out[1] = value >> 16 & 0xff
out[2] = value >> 8 & 0xff
out[3] = value & 0xff
out
end
def to_byte_array(num)
result = []
begin
result << (num & 0xff)
num >>= 8
end until (num == 0 || num == -1) && (result.last[7] == num[7])
result.reverse
end
def public_base64(key)
["ssh-rsa ", "\0\0\0\assh-rsa#{ sized_bytes(key.e) }#{ sized_bytes(key.n) }"].pack("a*m0")
end
def sized_bytes(value)
bytes = to_byte_array(value.to_i)
[bytes.size, *bytes].pack('NC*')
end
def to_byte_array(num, *significant)
return significant if num.between?(-1, 0) and significant[0][7] == num[7]
to_byte_array(*num.divmod(256)) + significant
end
@iain
Copy link
Copy Markdown

iain commented Jul 18, 2012

You're a wizard, Harry!

@igbanam
Copy link
Copy Markdown

igbanam commented Jul 18, 2012

I don't know what this code does but the refactoring is too good

@rkh
Copy link
Copy Markdown
Author

rkh commented Jul 18, 2012

Ah, it generates the encoded public SSH key (you can for instance then add to a repo on Github) from a pair of prime numbers (ie generated by the Ruby openssl lib). The pre-refactoring code is pretty much copied from the sshkey gem.

Usage:

require 'openssl'

key = OpenSSL::PKey::RSA.generate(2048)
puts public_base64(key.public_key)

@igbanam
Copy link
Copy Markdown

igbanam commented Jul 20, 2012

soo nice. thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment