· 8 years ago · Jan 26, 2018, 06:48 AM
1import base64
2import hashlib
3
4from Crypto.Cipher import AES
5
6class MulaEncryption:
7 # The block size to be used while padding
8 BS = 16
9
10 def __init__(self, secret_key, iv_key):
11 """Initialises the Class with the parameters passed.
12
13 :param secret_key:
14 The secret key to use in the symmetric cipher.
15 It must be 16 bytes long
16 :type secret_key: string
17
18 :param iv_key:
19 The initialization vector key to use in the symmetric cipher.
20 It must be 16 bytes long
21 :type iv_key: string
22 """
23
24 # Hash the secret key
25 self.secret_key_hash = hashlib.sha256(secret_key.encode()).hexdigest()[:32]
26
27 # Hash the IV Key
28 self.iv_hash = hashlib.sha256(iv_key.encode()).hexdigest()[:16]
29
30 def pad(self, string):
31 """Introduces extra bytes for strings less than the block size
32
33 :param string:
34 The string value of the text to be padded
35 :type string: string
36
37 :return: string
38 """
39 return string + (self.BS - len(string) % self.BS) * chr(self.BS - len(string) % self.BS)
40
41 def encrypt(self, params):
42 """Encrypts the params passed with the IV and secret key passed while initializing this class
43
44 :param params:
45 The string value of the text to be encrypted
46 :type params: string
47
48 :return: string: Encrypted string
49 """
50 cipher = AES.new(self.secret_key_hash.encode(), AES.MODE_CBC, self.iv_hash.encode())
51
52 string = cipher.encrypt(self.pad(params).encode())
53 return base64.b64encode(base64.b64encode(string))