> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cobrix.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Firmas HMAC paso a paso

> Cómo verificar de forma segura los dos protocolos de webhook

La firma permite demostrar que el cuerpo recibido fue generado por alguien que conoce el secreto y que no fue alterado durante el tránsito.

## Elige el protocolo correcto

**Webhooks generales**
`X-Cobrix-Signature: t=…,v1=…`
Firma `timestamp.raw_body` y acepta cualquier `2xx`.

**Documentos públicos**
`x-cobrix-signature: hex`
Firma solo `raw_body` y exige HTTP `200`.

## Protocolo general

Cobrix envía:

```http theme={null}
X-Cobrix-Signature: t=1784044800,v1=1f874cb4e61d06ea097ed49b9f6e3c1a94946de4445f3fc03b480c29846e5739
X-Cobrix-Timestamp: 1784044800
```

La fórmula exacta es:

```text theme={null}
signed_payload = timestamp + "." + raw_body
expected = HMAC_SHA256(secret, signed_payload).hex
```

**1. Captura el cuerpo crudo**

Obtén los bytes recibidos. Todavía no ejecutes `JSON.parse`.

**2. Extrae t y v1**

Del header de firma toma el timestamp `t` y el hexadecimal `v1`.

**3. Rechaza timestamps viejos**

Compara `t` con la hora Unix actual y admite como máximo 300 segundos de diferencia.

**4. Construye el mensaje**

Concatena el timestamp, un punto literal y el cuerpo exacto.

**5. Calcula y compara**

Calcula HMAC-SHA256 con el secreto y usa una comparación timing-safe.

```javascript Node.js theme={null}
import crypto from 'node:crypto'

export function verifyGeneralWebhook(rawBody, header, secret, now = Math.floor(Date.now() / 1000)) {
  const parts = Object.fromEntries(header.split(',').map(item => item.split('=')))
  const timestamp = Number(parts.t)
  if (!Number.isFinite(timestamp) || Math.abs(now - timestamp) > 300) return false

  const expected = crypto.createHmac('sha256', secret)
    .update(`${timestamp}.${rawBody.toString('utf8')}`)
    .digest()
  const received = Buffer.from(parts.v1 ?? '', 'hex')
  return received.length === expected.length && crypto.timingSafeEqual(received, expected)
}
```

```python Python theme={null}
import hashlib
import hmac
import time

def verify_general_webhook(raw_body: bytes, header: str, secret: str) -> bool:
    parts = dict(item.split('=', 1) for item in header.split(','))
    timestamp = int(parts.get('t', '0'))
    if abs(int(time.time()) - timestamp) > 300:
        return False
    signed = str(timestamp).encode() + b'.' + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(parts.get('v1', ''), expected)
```

```php PHP theme={null}
function verifyGeneralWebhook(string $rawBody, string $header, string $secret): bool {
    $parts = [];
    foreach (explode(',', $header) as $item) {
        [$key, $value] = array_pad(explode('=', $item, 2), 2, '');
        $parts[$key] = $value;
    }
    $timestamp = (int)($parts['t'] ?? 0);
    if (abs(time() - $timestamp) > 300) return false;
    $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    return hash_equals($expected, $parts['v1'] ?? '');
}
```

## Protocolo de documentos públicos

La fórmula no agrega timestamp:

```text theme={null}
expected = HMAC_SHA256(secret, raw_body).hex
```

```javascript Node.js theme={null}
import crypto from 'node:crypto'

export function verifyPublicDocumentWebhook(rawBody, signature, secret) {
  const expected = crypto.createHmac('sha256', secret).update(rawBody).digest()
  const received = Buffer.from(signature ?? '', 'hex')
  return received.length === expected.length && crypto.timingSafeEqual(received, expected)
}
```

```python Python theme={null}
import hashlib, hmac

def verify_public_document_webhook(raw_body: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature, expected)
```

```php PHP theme={null}
function verifyPublicDocumentWebhook(string $rawBody, string $signature, string $secret): bool {
    return hash_equals(hash_hmac('sha256', $rawBody, $secret), $signature);
}
```

## Fixture para probar tu implementación

| Valor | Contenido |
| - | - |
| Secreto | `whsec_fixture_123` |
| Timestamp | `1784044800` |
| Cuerpo | `{"id":"evt_fixture","event":"payment.succeeded","data":{"amountMinor":2025}}` |
| Firma esperada | `1f874cb4e61d06ea097ed49b9f6e3c1a94946de4445f3fc03b480c29846e5739` |

Si obtienes otro resultado, revisa codificación UTF-8, saltos de línea, espacios y el orden en que el framework procesa el cuerpo.

> [!WARNING]
>
> Nunca registres el secreto ni el header completo de firma en logs públicos. Para soporte basta con el identificador del evento y el resultado de la validación.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.