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