Programming

Lambda Function To Calculate A Checksum

Here’s a Lambda function to calculate a checksum. The JSON document will be passed in the body field and the script loads the JSON document using json.loads(). The MD5 checksum of the JSON document is calculated by encoding the JSON string as bytes, hashing it using hashlib.md5(), and returning the hexadecimal representation of the hash using hexdigest().

The response returns a 200 status code when successful, with the MD5 checksum as a string in the response body. If the JSON document is invalid and cannot be loaded, a 400 status code is returned with an error message in the response body. In the event of a 400, use the https://github.com/krypted/tinyconverters/blob/main/LintJSON.py linter to check the JSON document (or use it before).

import json
import hashlib
def calculate_json_checksum(event, context):
    # Retrieve the JSON document from the Lambda event
    json_document = event['body']
    # Load the JSON document
    try:
        data = json.loads(json_document)
    except json.JSONDecodeError:
        return {
            'statusCode': 400,
            'body': 'Invalid JSON document'
        }
    # Calculate the MD5 checksum of the JSON document
    checksum = hashlib.md5(json_document.encode()).hexdigest()
    return {
        'statusCode': 200,
        'body': checksum
    }



This is posted to a little repo I have of tiny converter microservices at https://github.com/krypted/tinyconverters/blob/main/md5_checksum_lambda.py