-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathkeyczar_util.py
77 lines (62 loc) · 1.82 KB
/
keyczar_util.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'''
Basic module to provide keyczar based encryption/decryption.
Deficiencies include:
* no key rotation
* no key expiration
Author: kvamlnk
'''
__metaclass__ = type
import os
from keyczar import keyczar
from keyczar import keyczart
from keyczar.errors import KeyczarError
# Note that the names used in these format strings
# should be used in your code
#
FMT_CREATE = 'create --location=%(loc)s --purpose=crypt'
FMT_ADDKEY = 'addkey --location=%(loc)s --status=primary'
#
def _require_dir( loc):
'''Make sure that loc is a directory.
If it does not exist, create it.
'''
if os.path.exists( loc):
if not os.path.isdir( loc):
raise ValueError( '%s must be a directory' % loc)
else:
# should we verify that containing dir is 0700?
os.makedirs( loc, 0755)
def _tool(fmt, **kwds):
'''Package the call to keyczart.main
which is awkwardly setup for command-line use without
organizing the underlying logic for direct function calls.
'''
return keyczart.main( (fmt % kwds).split() )
def _initialize(loc, **kwds):
'''Initialize a location
create it
add a primary key
'''
_require_dir( loc)
steps = [ FMT_CREATE, FMT_ADDKEY]
for step in steps:
_tool( step, loc=loc, **kwds)
class Crypter(object):
'''Simplify use of keyczar.Crypter class
'''
location = 'stdkeyset'
@staticmethod
def _read(loc):
return keyczar.Crypter.Read( loc)
def __init__( self, loc=None):
if loc is None:
loc = self.location
try:
self.crypt = self._read( loc)
except KeyczarError:
_initialize( loc)
self.crypt = self._read( loc)
def encrypt( self, s):
return self.crypt.Encrypt( s)
def decrypt( self, s):
return self.crypt.Decrypt( s)