forked from brasse/ciphersaber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cipherpickle.py
60 lines (42 loc) · 1.28 KB
/
cipherpickle.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
#!/bin/env python
import StringIO
import base64
try:
import cPickle as pickle
except:
import pickle
import ciphersaber
__N_DEFAULT = 20
def encrypt(plain_text, key, n=__N_DEFAULT):
fin = StringIO.StringIO(plain_text)
fout = StringIO.StringIO()
ciphersaber.process(True, fin, key, n, fout)
return base64.standard_b64encode(fout.getvalue())
def decrypt(encrypted_text, key, n=__N_DEFAULT):
fin = StringIO.StringIO(base64.standard_b64decode(encrypted_text))
fout = StringIO.StringIO()
ciphersaber.process(False, fin, key, n, fout)
return fout.getvalue()
def dumps(obj, key):
return encrypt(pickle.dumps(obj), key)
def loads(encrypted, key):
return pickle.loads(decrypt(encrypted, key))
def test():
obj = [[ i for i in range(50)],
[ i*i for i in range(50)],
[ i*i*i for i in range(50)],
[ i*i*i*i for i in range(50)],
]
key = 'secretkey'
encrypted = dumps(obj,key)
print obj
print encrypted
assert loads(encrypted,key) == obj
texts = [['Cipher Saver', '123456'],
['Test Test Test', 'qwe'], ]
for text, key in texts:
assert decrypt(encrypt(text,key),key) == text, 'Failed to encrypt/decrypt.'
def main():
test()
if __name__ == '__main__':
main()