stlinkv2.py now works with newer PyUSB
[gnuk/gnuk.git] / tool / get_raw_public_key.py
1 #! /usr/bin/python
2
3 import sys, binascii
4 from subprocess import check_output
5
6 def get_gpg_public_key(keygrip):
7     result = check_output(["gpg-connect-agent", "READKEY %s" % keygrip, "/bye"])
8     key = ""
9     while True:
10         i = result.find('%')
11         if i < 0:
12             key += result
13             break
14         hex_str = result[i+1:i+3]
15         key += result[0:i]
16         key += chr(int(hex_str,16))
17         result = result[i+3:]
18
19     pos = key.index("D (10:public-key(3:rsa(1:n257:") + 31 # skip NUL too
20     pos_last = key.index(")(1:e3:")
21     key = key[pos:pos_last]
22     if len(key) != 256:
23         raise ValueError, binascii.hexlify(key)
24     return key
25
26 if __name__ == '__main__':
27     keygrip = sys.argv[1]
28     k = get_gpg_public_key(keygrip)
29     shorthand = keygrip[0:8] + ".bin"
30     f = open(shorthand,"w")
31     f.write(k)
32     f.close()