from flask import Flask, request, Response
from flask_ngrok import run_with_ngrok
from Crypto.Cipher import AES, DES3, DES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
from base64 import b64encode, b64decode
# Initialising a web application with flask
# For this integration example, NGROK was used to emulate a response server
def encrypt(data, enckey, iv):
enckey = b64decode(enckey)
cipher = DES3.new(enckey, DES3.MODE_CBC, iv)
ct_bytes = cipher.encrypt(
pad(bytes(data, encoding='utf-8'), DES3.block_size))
ciphertext = b64encode(ct_bytes).decode('utf-8')
def decrypt(data, deckey, iv):
deckey = b64decode(deckey)
cipher = DES3.new(deckey, DES3.MODE_CBC, iv)
pt = unpad(cipher.decrypt(data), DES3.block_size)
except (ValueError, KeyError):
return 'Incorrect decryption'
@app.route('/get-post', methods=['POST'])
enckey = 'ENCRYPTION_KEY'
deckey = 'DECRYPTION_KEY'
# Retrieving the form sent by AnnA
# Recovering the received IV
ivReceived = data.get('ANNAEXEC')
# Creating the structure of an AnnA message
"PropValue": "Hello World!"
# Creating the container structure
"PropName": "Container001",
"PropValue": json.dumps(nodeMessage)
# Creating a new IV and encrypting it
key = get_random_bytes(8)
cipher = DES.new(key, DES3.MODE_CBC)
newIV = b64encode(cipher.iv).decode('utf-8')
# Serialising the container structure and encrypting it
serialisedContainer = json.dumps(container)
encryptedSerialisedContainer = encrypt(serialisedContainer, enckey, newIV)
newIVEncrypted = encrypt(newIV, deckey, ivReceived)
# Configuring response for AnnA
replyToAnnA = encryptedSerialisedContainer + ivReceived + newIVEncrypted
response = Response(replyToAnnA, content_type='text/plain')
print('\nData received from AnnA:', data)
print('\nIV Received:', ivReceived)
print('\nNode Message:', nodeMessage)
print('\nContainer:', container)
print('\nContainer Serialised:', serialisedContainer)
print('\nContainer Serialised Encrypted:', encryptedSerialisedContainer)
print('\nNew IV:', newIV)
print('\nNew IV Encrypted:', newIVEncrypted)
print('\nReply To AnnA:', replyToAnnA)
print('\nResponse From AnnA:', response)
if __name__ == '__main__':