7 from M2Crypto import RSA, DSA
10 def decode_key(fname):
11 """Convert base64 encoded openssh key to binary"""
12 contents = open(fname).read()
13 fields = contents.split()
18 if f.startswith("ssh-"):
22 return base64.b64decode(f)
27 # openssh binary key format
30 # length = 4 bytes (32-bit big-endian integer)
31 # data = length bytes of string
33 # sections of the key ( for RSA )
34 # [key-type (in ASCII)] [public exponent (bignum)] [primes (bignum)]
36 # sections of the key ( for DSA )
37 # [key-type (in ASCII)] [p (bignum)] [q (bignum)] [g (bignum)] [y (bignum)]
44 length = struct.unpack(">l", length)[0]
47 def read_values(key, count):
49 for i in range(count):
50 length, key = read_length(key)
56 length, key = read_length(key)
58 key_type = key[:length]
61 if key_type == "ssh-rsa":
62 # prepare parameters for RSA.new_pub_key
63 v = read_values(key, 2)
67 elif key_type == "ssh-dss":
68 # prepare parameters for DSA.set_params
69 v = read_values(key, 4)
70 p, q, g, y = v[0], v[1], v[2], v[3]
71 return key_type, p, q, g, y
74 def convert(fin, fout):
79 if key_type == "ssh-rsa":
81 rsa = RSA.new_pub_key((e, n))
84 elif key_type == "ssh-dss":
86 dsa = DSA.set_params(p, q, g)
88 dsa.save_pub_key(fout)
89 # FIXME: This is wrong.
90 # M2Crypto doesn't allow us to set the public key parameter
91 raise(Exception, "DSA keys are not supported yet: M2Crypto doesn't allow us to set the public key parameter")
94 if __name__ == "__main__":
95 if len(sys.argv) != 3:
96 print "Usage: %s <input-file> <output-file>"