Created
July 18, 2012 11:05
-
-
Save rkh/3135592 to your computer and use it in GitHub Desktop.
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
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 |
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 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 |
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)
soo nice. thanks!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't know what this code does but the refactoring is too good