Round #339
08 May 2026, 16:37· csharp· qwen2.5-coder-3b-instruct· r13-clean-hints
- Complexity
- band 0
- ZP / UO / OBS
- 5 / 4 / 1
- Journey weight
- 612
- Lightshift ΔL
- -0.50
Prompt
Implement a webhook delivery endpoint with HMAC signature verification
Zero-point index (what the engine surfaced)
ZPI-ZPI-0003 | 2026-05-08T16:37:14Z
Implement a webhook delivery endpoint with HMAC signature verification
ZERO POINT — 5 entries (structural invariants)
● hsl(27.69, 100%, 50%) async [feature]
● hsl(145.64, 100%, 27%) Task of T [feature]
● hsl(7.18, 100%, 38%) class [feature]
● hsl(0.00, 100%, 38%) public [feature]
● hsl(84.10, 100%, 38%) namespace [feature]
UNOBSERVED — 4 entries (implied truths)
○ hsl(9.23, 100%, 50%) interface [feature]
○ hsl(77.54, 100%, 36%) Routing middleware [function]
○ hsl(83.08, 100%, 42%) ILogger of T injection [function]
○ hsl(31.38, 100%, 42%) Scoped registration [function]
OBSERVED — 1 entries (explicit in request)
◉ hsl(98.46, 100%, 28%) with [feature]
COMPLEXITY │ 10 entries │ spread: 89° │ band: LOW
Baseline response (no ZPI)
To implement a webhook delivery endpoint with HMAC signature verification in C#, you need to follow these steps:
1. **Generate a Secret Key**: This key will be used to sign the payload of your webhook requests.
2. **Create a Signature**: When sending a request, calculate the HMAC signature using the secret key and the payload.
3. **Verify the Signature**: On receiving a request, verify that the received signature matches the calculated signature using the same secret key.
Here's a complete example in C#:
```csharp
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Web;
public class WebhookController : Controller
{
private readonly string _secretKey = "your_secret_key_here";
[HttpPost]
public IActionResult ReceiveWebhook([FromBody] dynamic payload)
{
// Extract the signature from the request headers
var receivedSignature = Request.Headers["X-Hub-Signature"];
if (string.IsNullOrEmpty(receivedSignature))
{
return BadRequest("Missing X-Hub-Signature header");
}
// Calculate the expected signature
string calculatedSignature = GenerateHmacSignature(payload.ToString());
// Verify the signatures
if (!VerifySignature(calculatedSignature, receivedSignature))
{
return Unauthorized("Invalid HMAC signature");
}
// Process the webhook payload
ProcessWebhookPayload(payload);
return Ok();
}
private string GenerateHmacSignature(string data)
{
using (var hmac = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(_secretKey)))
{
var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
return Convert.ToBase64String(hashBytes);
}
}
private bool VerifySignature(string calculatedSignature, string receivedSignature)
{
// The received signature is in the format "sha256=<signature>"
if (!receivedSignature.StartsWith("sha256="))
{
return false;
}
var expectedSignature = receivedSignature.Substring(7);
return calculatedSignature == expectedSignature;
}
private void ProcessWebhookPayload(dynamic payload)
{
// Implement your logic to process the webhook payload
Console.WriteLine($"Received webhook payload: {JsonConvert.SerializeObject(payload)}");
}
}
```
### Key Points:
- **Secret Key**: Replace `"your_secret_key_here"` with a secure secret key that you should keep confidential.
- **HMAC Signature Calculation**: The `GenerateHmacSignature` method computes the HMAC signature using SHA256.
- **Signature Verification**: The `VerifySignature` method checks if the received signature matches the calculated signature.
- **Payload Processing**: The `ProcessWebhookPayload` method is a placeholder for your logic to handle the webhook payload.
### Additional Considerations:
- **Environment Variables**: For production, consider storing sensitive information like the secret key in environment variables or a secure vault.
- **Error Handling**: Implement robust error handling and logging to manage unexpected situations.
- **Security**: Ensure that your webhook endpoint is only accessible over HTTPS to protect against man-in-the-middle attacks.
This example assumes you are using ASP.NET Core, but the logic can be adapted for other web frameworks as well.
Enhanced response (with ZPI)
To implement a webhook delivery endpoint with HMAC signature verification, we can use the `Microsoft.AspNetCore.Mvc` and `System.Text` namespaces for web request handling and string manipulation. We'll also use the `System.Security.Cryptography` namespace to generate and verify the HMAC signature.
Here's how you can implement this:
```csharp
using Microsoft.AspNetCore.Mvc;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
public class WebhookController : ControllerBase
{
private readonly ILogger<WebhookController> _logger;
public WebhookController(ILogger<WebhookController> logger)
{
_logger = logger;
}
[HttpPost("webhooks")]
public async Task<IActionResult> HandleWebhook([FromBody] string requestBody, [FromHeader(Name = "X-Hub-Signature")] string signature)
{
// Define the secret key used for HMAC verification
const string secretKey = "your-secret-key";
try
{
// Generate the expected HMAC signature from the request body and secret key
var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(requestBody));
var encodedSignature = Convert.ToBase64String(hashBytes);
// Verify the received signature against the expected signature
if (signature != $"sha256={encodedSignature}")
{
_logger.LogWarning("Invalid HMAC signature");
return Unauthorized();
}
// Process the webhook payload here
_logger.LogInformation("Webhook received and verified successfully");
// Example: Return a success response
return Ok(new { message = "Webhook processed successfully" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing webhook");
return StatusCode(500, "Internal Server Error");
}
}
}
```
### Explanation:
1. **Controller Setup**: The `WebhookController` class is decorated with `[ApiController]`, which enables automatic model binding and validation.
2. **Endpoint Definition**: The `HandleWebhook` method is an HTTP POST endpoint that accepts a JSON body (`[FromBody] string requestBody`) and a header for the HMAC signature (`[FromHeader(Name = "X-Hub-Signature")] string signature`).
3. **HMAC Verification**:
- We define a secret key used for generating the HMAC signature.
- We create an instance of `HMACSHA256` using the secret key.
- We compute the hash of the request body and convert it to a base64-encoded string.
- We compare this computed signature with the received signature. If they match, the webhook is verified.
4. **Error Handling**: Any exceptions during processing are caught and logged at the `Warning` level. A 500 Internal Server Error response is returned if an exception occurs.
5. **Logging**: The controller logs information about incoming webhooks and their verification status using the injected `ILogger`.
This implementation uses ASP.NET Core's built-in features for handling HTTP requests, model binding, and logging, ensuring a clean and efficient solution.
Grader chain
Each grader reads the same baseline + enhanced pair and casts an independent verdict. Disagreement is the framework's own signal — not noise to be averaged away.
V1claude-sonnet-4-6
WorseV4qwen2.5-coder-7b-instruct
BetterComments
Our grader said what it said. What do you say? Comment as a guest below.
No comments yet. Be the first to say what you make of this round.