/
ticket.py
43 lines (37 loc) · 1.32 KB
/
ticket.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""An extremely simple interface to the signing/verifying capabilities
of gnupg.
You must already have the key in the keyring.
"""
from subprocess import PIPE, Popen
from xmlrpc.client import dumps, loads
# see also myplc/plc.d/gpg
import os.path
GPG = '/usr/bin/gpg1' if os.path.exists("/usr/bin/gpg1") else "/usr/bin/gpg"
def _popen_gpg(*args):
"""Return a Popen object to GPG."""
return Popen((GPG, '--batch', '--no-tty') + args,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
def sign(data):
"""Return <data> signed with the default GPG key."""
msg = dumps((data,), methodresponse = True)
p = _popen_gpg('--armor', '--sign', '--keyring', '/etc/planetlab/secring.gpg', '--no-default-keyring')
p.stdin.write(msg)
p.stdin.close()
signed_msg = p.stdout.read()
p.stdout.close()
p.stderr.close()
p.wait()
return signed_msg
def verify(signed_msg):
"""If <signed_msg> is a valid signed document, return its contents. Otherwise, return None."""
p = _popen_gpg('--decrypt', '--keyring', '/usr/boot/pubring.gpg', '--no-default-keyring')
p.stdin.write(signed_msg)
p.stdin.close()
msg = p.stdout.read()
p.stdout.close()
p.stderr.close()
if p.wait():
return None # verification failed
else:
data, = loads(msg)[0]
return data