7 from M2Crypto import RSA, DSA, m2
10 ###### Workaround for bug in m2crypto-0.18 (on Fedora 8)
11 class RSA_pub_fix(RSA.RSA_pub):
12 def save_key_bio(self, bio, *args, **kw):
13 return self.save_pub_key_bio(bio)
15 def rsa_new_pub_key(couple):
20 return RSA_pub_fix(rsa, 1)
22 #rsa_new_pub_key = RSA.new_pub_key
25 def decode_key(fname):
26 """Convert base64 encoded openssh key to binary"""
27 contents = open(fname).read()
28 fields = contents.split()
33 if f.startswith("ssh-"):
37 return base64.b64decode(f)
42 # openssh binary key format
45 # length = 4 bytes (32-bit big-endian integer)
46 # data = length bytes of string
48 # sections of the key ( for RSA )
49 # [key-type (in ASCII)] [public exponent (bignum)] [primes (bignum)]
51 # sections of the key ( for DSA )
52 # [key-type (in ASCII)] [p (bignum)] [q (bignum)] [g (bignum)] [y (bignum)]
59 length = struct.unpack(">l", length)[0]
62 def read_values(key, count):
64 for i in range(count):
65 length, key = read_length(key)
71 length, key = read_length(key)
73 key_type = key[:length]
76 if key_type == "ssh-rsa":
77 # prepare parameters for RSA.new_pub_key
78 v = read_values(key, 2)
82 elif key_type == "ssh-dss":
83 # prepare parameters for DSA.set_params
84 v = read_values(key, 4)
85 p, q, g, y = v[0], v[1], v[2], v[3]
86 return key_type, p, q, g, y
89 def convert(fin, fout):
94 if key_type == "ssh-rsa":
96 rsa = rsa_new_pub_key((e, n))
99 elif key_type == "ssh-dss":
101 dsa = DSA.set_params(p, q, g)
103 dsa.save_pub_key(fout)
104 # FIXME: This is wrong.
105 # M2Crypto doesn't allow us to set the public key parameter
106 raise Exception("DSA keys are not supported yet: M2Crypto doesn't allow us to set the public key parameter")
109 if __name__ == "__main__":
110 if len(sys.argv) != 3:
111 print "Usage: %s <input-file> <output-file>"