1 from zeroinstall
.injector
import gpg
2 import tempfile
, os
, base64
, sys
, shutil
4 def check_signature(path
):
5 data
= file(path
).read()
6 xml_comment
= data
.rfind('\n<!-- Base64 Signature')
8 data_stream
, sigs
= gpg
.check_stream(file(path
))
10 data
= data
[:xml_comment
+ 1]
12 elif data
.startswith('-----BEGIN'):
13 data_stream
, sigs
= gpg
.check_stream(file(path
))
15 data
= data_stream
.read()
17 return data
, sign_unsigned
, None
19 if isinstance(sig
, gpg
.ValidSig
):
20 return data
, sign_fn
, sig
.fingerprint
21 print "ERROR: No valid signatures found!"
24 ok
= raw_input('Ignore and load anyway? (y/N) ').lower()
25 if ok
and 'yes'.startswith(ok
):
26 return data
, sign_unsigned
, None
29 def write_tmp(path
, data
):
30 """Create a temporary file in the same directory as 'path' and write data to it."""
31 fd
, tmp
= tempfile
.mkstemp(prefix
= 'tmp-', dir = os
.path
.dirname(path
))
32 stream
= os
.fdopen(fd
, 'w')
37 def run_gpg(default_key
, *arguments
):
38 arguments
= list(arguments
)
39 if default_key
is not None:
40 arguments
= ['--default-key', default_key
] + arguments
41 arguments
.insert(0, 'gpg')
42 if os
.spawnvp(os
.P_WAIT
, 'gpg', arguments
):
43 raise Exception("Command '%s' failed" % arguments
)
45 def sign_unsigned(path
, data
, key
):
46 os
.rename(write_tmp(path
, data
), path
)
48 def sign_plain(path
, data
, key
):
49 tmp
= write_tmp(path
, data
)
51 run_gpg(key
, '--clearsign', tmp
)
54 os
.rename(tmp
+ '.asc', path
)
56 def sign_xml(path
, data
, key
):
57 tmp
= write_tmp(path
, data
)
59 run_gpg(key
, '--detach-sign', tmp
)
63 encoded
= base64
.encodestring(file(tmp
).read())
65 sig
= "<!-- Base64 Signature\n" + encoded
+ "\n-->\n"
66 os
.rename(write_tmp(path
, data
+ sig
), path
)
68 def export_key(dir, fingerprint
):
69 assert fingerprint
is not None
70 # Convert fingerprint to key ID
71 stream
= os
.popen('gpg --with-colons --list-keys %s' % fingerprint
)
75 parts
= line
.split(':')
78 raise Exception('Two key IDs returned from GPG!')
82 key_file
= os
.path
.join(dir, keyID
+ '.gpg')
83 if os
.path
.isfile(key_file
):
85 key_stream
= file(key_file
, 'w')
86 stream
= os
.popen("gpg -a --export '%s'" % fingerprint
)
87 shutil
.copyfileobj(stream
, key_stream
)
90 print "Exported public key as '%s'" % key_file