· 7 years ago · Apr 04, 2018, 07:22 PM
1from hashlib import md5
2from base64 import b64decode
3from base64 import b64encode
4from Crypto import Random
5from Crypto.Cipher import AES
6
7SECRET_KEY = 'anything'
8
9
10BLOCK_SIZE = 16 # Bytes
11
12
13def pad(s):
14 number_character_will_pad = BLOCK_SIZE - len(s) % BLOCK_SIZE
15 pad_character = chr(number_character_will_pad)
16 return s + number_character_will_pad * pad_character
17
18
19def unpad(s):
20 pad_character = s[len(s) - 1:]
21 number_pad_character = ord(pad_character)
22 return s[:-number_pad_character]
23
24
25class AESCipher:
26 def __init__(self):
27 self.key = md5(SECRET_KEY.encode('utf8')).hexdigest()
28
29 def encrypt(self, raw):
30 raw = pad(raw)
31 iv = Random.new().read(BLOCK_SIZE)
32 cipher = AES.new(self.key, AES.MODE_CBC, iv)
33 return b64encode(iv + cipher.encrypt(raw))
34
35 def decrypt(self, enc):
36 enc = b64decode(enc)
37 iv = enc[:BLOCK_SIZE]
38 cipher = AES.new(self.key, AES.MODE_CBC, iv)
39 return unpad(cipher.decrypt(enc[16:])).decode('utf8')
40
41
42## Usage
43encrypt_message = AESCipher().encrypt('secret message')
44message = AESCipher().decrypt(encrypt_message)