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