coding utf-8 import json from itsdangerous import URLSafeTimedSerializ

 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
# -*- coding: utf-8 -*-
import json
from itsdangerous import URLSafeTimedSerializer as ExpiredSigner
from itsdangerous import URLSafeSerializer as Signer
class CryptoSessionCookies(object):
max_age = None
def __init__(self, secret_key, max_age=None):
"""
data should contains dict of stored values
max_age in days or None if don't need
"""
self.signer = Signer(secret_key)
if max_age is not None:
self.signer = ExpiredSigner(secret_key)
self.max_age = max_age * 60 * 60 * 24
def crypt(self, data):
crypt_data = self.signer.dumps(data)
return crypt_data
def decrypt(self, data, max_age=None):
if max_age is None:
decrypt_data = self.signer.loads(data)
else:
if max_age is None:
max_age = self.max_age or (365 * 60 * 60 * 24)
else:
max_age = max_age * 60 * 60 * 24
decrypt_data = self.signer.loads(data, max_age=max_age)
return decrypt_data
def tests():
data = {'user': 'vadim', 'email': 'vaidm@gmail.com'}
signer = CryptoSessionCookies('secret-key')
crypted_value = signer.crypt(data)
decrypted_value = signer.decrypt(crypted_value)
if json.dumps(data) == json.dumps(decrypted_value):
print "OK"
else:
print "Fail"
if __name__ == '__main__':
tests()