// Verificación de la firma de un aviso de webhook de Digitaldocu eFactura (Standard Webhooks). // // dotnet run -- prueba // dotnet run -- comprobar ID SELLO FIRMA FICHERO_CUERPO [--ahora SEGUNDOS] (secreto en EFACTURA_WEBHOOK_SECRETO) // // Copia `Webhook.Verificar` en tu receptor. Responde 2xx enseguida y lee el canal de cambios // fuera de la petición: el webhook es un despertador; el canal, la verdad. using System.Security.Cryptography; using System.Text; namespace Efactura.Ejemplo; public sealed class FirmaNoValida(string motivo) : Exception(motivo); public static class Webhook { public const int Tolerancia = 5 * 60; // segundos, en los dos sentidos /// El webhook-id si la firma vale; si no, lanza FirmaNoValida. public static string Verificar(string secreto, string? id, string? sello, string? firmas, byte[] cuerpo, long? ahora = null) { if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(sello) || string.IsNullOrEmpty(firmas)) throw new FirmaNoValida("faltan cabeceras"); if (!long.TryParse(sello, out var segundos)) throw new FirmaNoValida("sello no válido"); var reloj = ahora ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds(); if (Math.Abs(reloj - segundos) > Tolerancia) throw new FirmaNoValida("sello fuera de la ventana de 5 minutos"); if (!secreto.StartsWith("whsec_", StringComparison.Ordinal)) throw new ArgumentException("el secreto empieza por whsec_"); var clave = Convert.FromBase64String(secreto["whsec_".Length..]); var firmado = Encoding.UTF8.GetBytes($"{id}.{sello}.").Concat(cuerpo).ToArray(); var esperada = Encoding.ASCII.GetBytes("v1," + Convert.ToBase64String(HMACSHA256.HashData(clave, firmado))); // Durante una rotación llegan dos firmas separadas por un espacio: basta con una. foreach (var recibida in firmas.Split(' ', StringSplitOptions.RemoveEmptyEntries)) if (CryptographicOperations.FixedTimeEquals(esperada, Encoding.ASCII.GetBytes(recibida))) return id; throw new FirmaNoValida("ninguna firma cuadra"); } } public static class Programa { public static int Main(string[] args) { if (args.Length >= 1 && args[0] == "prueba") return Prueba(); if (args.Length >= 5 && args[0] == "comprobar") { var secreto = Environment.GetEnvironmentVariable("EFACTURA_WEBHOOK_SECRETO") ?? ""; long? ahora = null; var i = Array.IndexOf(args, "--ahora"); if (i > 0 && i + 1 < args.Length) ahora = long.Parse(args[i + 1]); try { var id = Webhook.Verificar(secreto, args[1], args[2], args[3], File.ReadAllBytes(args[4]), ahora); Console.WriteLine($"{{\"valida\": true, \"id\": \"{id}\"}}"); return 0; } catch (FirmaNoValida e) { Console.WriteLine($"{{\"valida\": false, \"motivo\": \"{e.Message}\"}}"); return 1; } } Console.Error.WriteLine("uso: prueba | comprobar ID SELLO FIRMA FICHERO_CUERPO [--ahora SEGUNDOS]"); return 2; } // El mismo ejemplo fijo que ejemplos/python/receptor_webhook.py. static int Prueba() { var clave = Enumerable.Range(0, 32).Select(b => (byte)b).ToArray(); var secreto = "whsec_" + Convert.ToBase64String(clave); const string id = "msg_ejemplo00000000000000000", sello = "1800000000"; var cuerpo = Encoding.UTF8.GetBytes("{\"id\":\"msg_ejemplo00000000000000000\",\"tipo\":\"emitidas.cambios\"," + "\"creado\":\"2027-01-15T08:00:00Z\",\"suscripcion\":\"wh_ejemplo0000000000000\"}"); var firma = "v1," + Convert.ToBase64String( HMACSHA256.HashData(clave, Encoding.UTF8.GetBytes($"{id}.{sello}.").Concat(cuerpo).ToArray())); Webhook.Verificar(secreto, id, sello, firma, cuerpo, 1800000000 + 299); foreach (var (s, ahora) in new[] { ("1800000001", 1800000000L), (sello, 1800000000L - 301) }) { try { Webhook.Verificar(secreto, id, s, firma, cuerpo, ahora); return 1; } catch (FirmaNoValida) { } } Console.WriteLine("firma válida; la manipulada y la de fuera de la ventana, rechazadas"); return 0; } }