Categories

Message Validation

Connecta can send out message with a signature that can be used to validate the contents of the message. This confirms the message is actually coming from the trusted source.

Here's how to validate the messages as the receiving party:

Python:

import hmac
import hashlib
import base64

# Simulated incoming request
incoming_request = {
    "headers": {
        "X-Signature": "base64_encoded_signature_here"  # Example: replace with actual base64 signature
    },
    "body": b"Plain text message"  # Raw payload bytes as received (text, JSON, XML, etc.)
}

# Shared secret key (must be bytes)
secret_key = b"your_shared_secret_key"

# Step 1: Extract the raw payload bytes from the request body
received_payload_bytes = incoming_request["body"]

# Step 2: Decode the base64-encoded signature from the header
received_signature = base64.b64decode(incoming_request["headers"]["X-Signature"])

# Step 3: Recalculate the HMAC signature using the same secret key
expected_signature = hmac.new(secret_key, received_payload_bytes, hashlib.sha256).digest()

# Step 4: Compare the received signature with the expected signature
if hmac.compare_digest(received_signature, expected_signature):
    print("Message is valid and authentic.")
else:
    print("Message verification failed. Possible tampering or incorrect key.")

PHP:

<?php
// Simulated incoming request
$incoming_request = [
    "headers" => [
        "X-Signature" => "base64_encoded_signature_here"  // Replace with actual base64 signature
    ],
    "body" => "Plain text message"  // Raw payload as received
];

// Shared secret key (must be bytes)
$secret_key = "your_shared_secret_key";

// Step 1: Get the raw payload bytes
$received_payload = $incoming_request["body"];

// Step 2: Decode the base64-encoded signature from the header
$received_signature = base64_decode($incoming_request["headers"]["X-Signature"]);

// Step 3: Recalculate the HMAC signature using the same secret key
$expected_signature = hash_hmac('sha256', $received_payload, $secret_key, true);

// Step 4: Compare the received signature with the expected signature
if (hash_equals($received_signature, $expected_signature)) {
    echo "Message is valid and authentic.";
} else {
    echo "Message verification failed. Possible tampering or incorrect key.";
}
?>




Validation Secret Key