Coverage for encryption_util.py: 94%

32 statements  

« 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 

6 

7def encrypt_data(key, data): 

8 ''' 

9 Encrypts the specified plain text using AES/GCM/NoPadding. 

10  

11 Parameters: 

12 

13 ``key`` (string): The Shared Key. 

14 

15 ``data`` (string): The Raw Data to be Encrypted. 

16 

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  

26 

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()) 

31 

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) 

41 

42 # Return the Encrypted Data.  

43 return encrypted_data 

44 

45def decrypt_data(key, e_data): 

46 ''' 

47 Decrypts the Encrypted Data using Shared Key. 

48 

49 Parameters: 

50 

51 ``key`` (string): The Shared Key 

52  

53 ``data`` (string): The Encrypted Data. 

54 

55 Returns: 

56 string: The Raw Decrypted data 

57 ''' 

58 decrypted_data=None 

59 try: 

60 

61 shared_key = base64.b64decode(key) 

62 

63 # Decode the base64 string and De-serialize it as 

64 decoded_payload = json.loads(base64.b64decode(e_data)) 

65 

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"]) 

70 

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 

78