· 8 years ago · Jan 26, 2018, 07:04 AM
1import base64
2import hashlib
3
4from Crypto.Cipher import AES
5
6
7class DecryptParameters:
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 un_pad(self, string):
32 """Removes extra bytes formally inserted for strings less than the block size
33
34 :param string:
35 The string value of the text to be un padded
36 :type string: string
37
38 :return: string
39 """
40 return string[:-ord(string[len(string) - 1:])]
41
42 def decrypt(self, encrypted_string):
43 """Decrypts the encoded string passed with the IV and secret key passed while initializing this class
44
45 :param encrypted_string:
46 The string to be decrypted
47 :type encrypted_string: string
48
49 :return: string: Decrypted string
50 """
51 cipher = AES.new(self.secret_key_hash.encode(), AES.MODE_CBC, self.iv_hash.encode())
52
53 string = base64.b64decode(base64.b64decode(encrypted_string))
54 string = cipher.decrypt(string)
55
56 return self.un_pad(string.decode())