NeuroAgent

Avito Webhook Signature Algorithm: HMAC-SHA256 Guide

Complete guide to HMAC-SHA256 algorithm for Avito webhook signature. Learn how to generate and verify the x-avito-messenger-signature for secure integration.

Question

What algorithm is used to generate the ‘x-avito-messenger-signature’ in Avito’s webhook API? It’s necessary to understand the mechanism for generating this signature to verify incoming requests from Avito.

NeuroAgent

Avito Webhook Signature Verification

For the ‘x-avito-messenger-signature’ signature in the Avito webhook API, the HMAC algorithm with the SHA-256 hash function is used. The signature is generated by calculating the HMAC hash of the request body using the secret key provided by Avito, and comparing the resulting value with the signature passed in the request header.

Table of Contents

Signature Generation Algorithm

The ‘x-avito-messenger-signature’ signature is formed using the cryptographic HMAC (Hash-based Message Authentication Code) algorithm with the SHA-256 hash function.

How HMAC Works

HMAC is a message authentication mechanism that uses a cryptographic hash function along with a secret key to ensure data integrity and authenticity. In the case of the Avito webhook API, the process works as follows:

  1. Secret Key: Avito provides you with a secret key that must be stored securely and never shared with third parties.

  2. Request Body: The HTTP request body (payload) is used as the message for hashing.

  3. Hashing: HMAC hashing is performed using SHA-256:

    signature = HMAC-SHA256(secret_key, payload)
    
  4. Formatting: The resulting hash is formatted as a string with the “sha256=” prefix:

    formatted_signature = "sha256=" + hex(digest)
    

Header Structure

The ‘x-avito-messenger-signature’ header contains the signature in the following format:

x-avito-messenger-signature: sha256=your_hash_in_hex_format

Verification Process

To verify the authenticity of incoming requests from Avito, follow these steps:

Step 1: Data Extraction

  1. Get the value of the x-avito-messenger-signature header from the HTTP request
  2. Save the request body in its original form (unchanged)
  3. Use the secret key provided by Avito

Step 2: Generate Expected Signature

  1. Perform HMAC-SHA256 hashing of the request body using the secret key
  2. Convert the result to a hexadecimal string
  3. Add the “sha256=” prefix to the result

Step 3: Compare Signatures

  1. Compare the generated signature with the one received from the header
  2. Use timing-safe comparison to prevent timing attacks

Important: When comparing signatures, always use specialized timing-safe comparison functions, not simple string comparison, to prevent timing attacks.


Implementation Examples

Python Implementation

python
import hmac
import hashlib
import json

def verify_avito_signature(payload, signature, secret_key):
    """
    Verify Avito webhook signature
    
    :param payload: Raw request body bytes
    :param signature: Signature from x-avito-messenger-signature header
    :param secret_key: Secret key provided by Avito
    :return: True if signature is valid, False otherwise
    """
    # Generate expected signature
    digest = hmac.new(
        secret_key.encode('utf-8'),
        payload,
        hashlib.sha256
    ).hexdigest()
    
    expected_signature = f"sha256={digest}"
    
    # Use timing-safe comparison
    return hmac.compare_digest(signature, expected_signature)

# Flask example
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.post('/webhook')
def webhook_handler():
    # Get signature from header
    signature = request.headers.get('x-avito-messenger-signature')
    
    # Get raw body
    payload = request.get_data()
    
    # Your secret key from Avito
    AVITO_SECRET_KEY = 'your-secret-key-here'
    
    # Verify signature
    if not verify_avito_signature(payload, signature, AVITO_SECRET_KEY):
        return jsonify({'error': 'Invalid signature'}), 401
    
    # Process webhook data
    data = request.get_json()
    
    # Your business logic here
    return jsonify({'status': 'success'}), 200

JavaScript (Node.js) Implementation

javascript
const crypto = require('crypto');

function verifyAvitoSignature(payload, signature, secretKey) {
    // Generate expected signature
    const hmac = crypto.createHmac('sha256', secretKey);
    hmac.update(payload);
    const digest = hmac.digest('hex');
    const expectedSignature = `sha256=${digest}`;
    
    // Use timing-safe comparison
    return crypto.timingSafeEqual(
        Buffer.from(signature, 'utf8'),
        Buffer.from(expectedSignature, 'utf8')
    );
}

// Express.js example
const express = require('express');
const app = express();

app.use(express.raw({ type: 'application/json' }));

app.post('/webhook', (req, res) => {
    const signature = req.get('x-avito-messenger-signature');
    const payload = req.body;
    
    const AVITO_SECRET_KEY = 'your-secret-key-here';
    
    if (!verifyAvitoSignature(payload, signature, AVITO_SECRET_KEY)) {
        return res.status(401).json({ error: 'Invalid signature' });
    }
    
    const data = JSON.parse(payload.toString());
    
    // Your business logic here
    res.json({ status: 'success' });
});

Security Recommendations

Secure Storage of Secret Keys

  1. Don’t store keys in code: Use environment variables or secret management systems
  2. Regular key rotation: Periodically change secret keys
  3. Limited access: Grant access to keys only to necessary systems

Protection Against Attacks

  1. HTTPS: Always use HTTPS for transmitting webhook data
  2. IP whitelisting: Restrict request acceptance only to trusted Avito IP addresses
  3. Logging: Keep logs of all signature verifications for auditing

Performance

  1. Caching: If possible, cache verification results for frequently repeated requests
  2. Asynchronous processing: Process valid requests asynchronously for quick response to Avito

Common Issues and Solutions

Issue: Signature Mismatch

Symptom: You generate a signature, but it doesn’t match the one received from Avito.

Possible causes:

  • Incorrect secret key
  • Modification of the request body (adding/removing spaces, changing encoding)
  • Incorrect signature formatting

Solutions:

  1. Verify the correctness of the secret key
  2. Ensure you’re using the original request body without modifications
  3. Check the signature format (should have the “sha256=” prefix)

Issue: Performance

Symptom: Signature verification takes too much time.

Solutions:

  1. Use more efficient cryptographic libraries
  2. Implement parallel processing
  3. Consider using hardware acceleration for cryptographic operations

Issue: Security

Symptom: Suspicions of hacking or key compromise.

Solutions:

  1. Immediately change the secret key
  2. Check logs for suspicious activity
  3. Increase key rotation frequency

Sources

  1. Avito Developer Portal - Messenger API
  2. HMAC Webhook Authentication: Complete Guide + Code Examples
  3. Webhook Signature Verification | IDaaS API Client Documentation
  4. Authentication & Verification | Hookdeck Event Gateway Docs
  5. HMAC Validation in ServiceNow: Securing Webhook Integrations with CertificateEncryption

Conclusion

Understanding the ‘x-avito-messenger-signature’ signature generation mechanism is critical for secure integration with the Avito webhook API. Key points:

  1. Algorithm: HMAC-SHA256 is used to generate the signature
  2. Format: Signatures always start with the “sha256=” prefix
  3. Verification: Requires timing-safe signature comparison to prevent timing attacks
  4. Security: Secret keys must be stored securely and regularly rotated

For successful implementation, it’s recommended to thoroughly test the verification mechanism in a development environment before deploying to production. Always use modern cryptographic libraries and follow security best practices when working with webhook requests.