-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypticle.py
More file actions
63 lines (53 loc) · 2.3 KB
/
crypticle.py
File metadata and controls
63 lines (53 loc) · 2.3 KB
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
import cPickle as pickle
import hashlib
import hmac
import os
from Crypto.Cipher import AES
class AuthenticationError(Exception): pass
class Crypticle(object):
PICKLE_PAD = "pickle::"
AES_BLOCK_SIZE = 16
SIG_SIZE = hashlib.sha256().digest_size
def __init__(self, key_string, key_size=192):
self.keys = self.extract_keys(key_string, key_size)
self.key_size = key_size
@classmethod
def generate_key_string(cls, key_size=192):
key = os.urandom(key_size / 8 + cls.SIG_SIZE)
return key.encode("base64").replace("\n", "")
@classmethod
def extract_keys(cls, key_string, key_size):
key = key_string.decode("base64")
assert len(key) == key_size / 8 + cls.SIG_SIZE, "invalid key"
return key[:-cls.SIG_SIZE], key[-cls.SIG_SIZE:]
def encrypt(self, data):
"""encrypt data with AES-CBC and sign it with HMAC-SHA256"""
aes_key, hmac_key = self.keys
pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
data = data + pad * chr(pad)
iv_bytes = os.urandom(self.AES_BLOCK_SIZE)
cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
data = iv_bytes + cypher.encrypt(data)
sig = hmac.new(hmac_key, data, hashlib.sha256).digest()
return data + sig
def decrypt(self, data):
"""verify HMAC-SHA256 signature and decrypt data with AES-CBC"""
aes_key, hmac_key = self.keys
sig = data[-self.SIG_SIZE:]
data = data[:-self.SIG_SIZE]
if hmac.new(hmac_key, data, hashlib.sha256).digest() != sig:
raise AuthenticationError("message authentication failed")
iv_bytes = data[:self.AES_BLOCK_SIZE]
data = data[self.AES_BLOCK_SIZE:]
cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
data = cypher.decrypt(data)
return data[:-ord(data[-1])]
def dumps(self, obj, pickler=pickle):
"""pickle and encrypt a python object"""
return self.encrypt(self.PICKLE_PAD + pickler.dumps(obj))
def loads(self, data, pickler=pickle):
"""decrypt and unpickle a python object"""
data = self.decrypt(data)
# simple integrity check to verify that we got meaningful data
assert data.startswith(self.PICKLE_PAD), "unexpected header"
return pickler.loads(data[len(self.PICKLE_PAD):])