This repository was archived by the owner on Nov 29, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathencryption.py
More file actions
84 lines (63 loc) · 2.53 KB
/
Copy pathencryption.py
File metadata and controls
84 lines (63 loc) · 2.53 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""A few symmetric encryption routines"""
import base64
from os import urandom
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding, hashes
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
class Encryptor(object):
def encrypt(self, message):
raise NotImplementedError()
class Decryptor(object):
def decrypt(self, message):
raise NotImplementedError()
class AESDecryptor(Decryptor):
"""A decryptor that uses AES symmetric keys"""
IV_ENC_LENGTH = 24 # 4/3 of IV_LENGTH due to base64
BLOCK_LENGTH = 128
def __init__(self, password, backend=None):
backend = backend or default_backend()
self.backend = backend
self.password = password
def decrypt(self, message):
iv = base64.b64decode(message[:self.IV_ENC_LENGTH])
cipher = Cipher(
algorithms.AES(self.password),
modes.CBC(iv), backend=self.backend)
message = base64.b64decode(message[self.IV_ENC_LENGTH:])
decryptor = cipher.decryptor()
padded = decryptor.update(message)
padded += decryptor.finalize()
unpadder = padding.PKCS7(self.BLOCK_LENGTH).unpadder()
decrypted = unpadder.update(padded)
decrypted += unpadder.finalize()
return decrypted
class AESEncryptor(Encryptor):
"""An encryptor that uses AES symmetric keys"""
IV_LENGTH = 16
BLOCK_LENGTH = 128
def __init__(self, password, backend=None):
backend = backend or default_backend()
self.backend = backend
self.password = password
def encrypt(self, message):
iv = urandom(self.IV_LENGTH)
cipher = Cipher(
algorithms.AES(self.password),
modes.CBC(iv), backend=self.backend)
encryptor = cipher.encryptor()
padder = padding.PKCS7(self.BLOCK_LENGTH).padder()
padded = padder.update(message)
padded += padder.finalize()
encrypted = encryptor.update(padded)
encrypted += encryptor.finalize()
return base64.b64encode(iv) + base64.b64encode(encrypted)
class AESCryptor(AESDecryptor, AESEncryptor):
pass
class MediactiveAESCryptor(AESCryptor):
"""Mediactive uses the SHA hash of the key as a key"""
def __init__(self, password):
backend = default_backend()
digest = hashes.Hash(hashes.SHA256(), backend=backend)
digest.update(password)
password = digest.finalize()
super(MediactiveAESCryptor, self).__init__(password, backend)