Coverage for encryption_util.py: 94%
32 statements
« prev ^ index » next coverage.py v7.2.6, created at 2023-05-29 15:32 +0530
« prev ^ index » next coverage.py v7.2.6, created at 2023-05-29 15:32 +0530
1import base64
2import json
3from Cryptodome.Cipher import AES
4from Crypto.Random import get_random_bytes
5import logging
7def encrypt_data(key, data):
8 '''
9 Encrypts the specified plain text using AES/GCM/NoPadding.
11 Parameters:
13 ``key`` (string): The Shared Key.
15 ``data`` (string): The Raw Data to be Encrypted.
17 Returns:
18 string: The Encrypted data in base64 encoded string format
19 '''
20 # The standard Initialization Vector (IV) length (96 bits) (12 byte).
21 IV_BYTE_LENGTH=12
22 encrypted_data=None
23 try:
24 shared_key = base64.b64decode(key)
25 nonce = get_random_bytes(IV_BYTE_LENGTH) # Randomly generate the IV/nonce
27 # Initialize AES/GCM cipher for encryption
28 cipher = AES.new(shared_key, AES.MODE_GCM, nonce=nonce)
29 # Encrypt the raw data and get the cipher text and authentication tag.
30 ciphertext, auth_tag = cipher.encrypt_and_digest(data.encode())
32 # Set the values for the EncryptedData
33 encrypted_payload = {
34 'nonce': base64.b64encode(cipher.nonce).decode("utf-8"),
35 'encrypted_data': base64.b64encode(ciphertext).decode("utf-8"),
36 'hmac': base64.b64encode(auth_tag).decode("utf-8")
37 }
38 encrypted_data=base64.b64encode(json.dumps(encrypted_payload).encode()).decode("utf-8")
39 except Exception as e:
40 logging.exception(e)
42 # Return the Encrypted Data.
43 return encrypted_data
45def decrypt_data(key, e_data):
46 '''
47 Decrypts the Encrypted Data using Shared Key.
49 Parameters:
51 ``key`` (string): The Shared Key
53 ``data`` (string): The Encrypted Data.
55 Returns:
56 string: The Raw Decrypted data
57 '''
58 decrypted_data=None
59 try:
61 shared_key = base64.b64decode(key)
63 # Decode the base64 string and De-serialize it as
64 decoded_payload = json.loads(base64.b64decode(e_data))
66 # Decode the fields of encryptedData from base64 to bytes.
67 nonce = base64.b64decode(decoded_payload["nonce"])
68 encrypted_data = base64.b64decode( decoded_payload["encrypted_data"])
69 auth_tag =base64.b64decode( decoded_payload["hmac"])
71 cipher = AES.new(shared_key, AES.MODE_GCM, nonce=nonce)
72 # Decrypt the data
73 plaintext = cipher.decrypt_and_verify(encrypted_data, auth_tag)
74 decrypted_data=plaintext.decode('utf-8')
75 except Exception as e:
76 logging.exception(e)
77 return decrypted_data