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.
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
- Verification Process
- Implementation Examples
- Security Recommendations
- Common Issues and Solutions
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:
-
Secret Key: Avito provides you with a secret key that must be stored securely and never shared with third parties.
-
Request Body: The HTTP request body (payload) is used as the message for hashing.
-
Hashing: HMAC hashing is performed using SHA-256:
signature = HMAC-SHA256(secret_key, payload) -
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
- Get the value of the
x-avito-messenger-signatureheader from the HTTP request - Save the request body in its original form (unchanged)
- Use the secret key provided by Avito
Step 2: Generate Expected Signature
- Perform HMAC-SHA256 hashing of the request body using the secret key
- Convert the result to a hexadecimal string
- Add the “sha256=” prefix to the result
Step 3: Compare Signatures
- Compare the generated signature with the one received from the header
- 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
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
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
- Don’t store keys in code: Use environment variables or secret management systems
- Regular key rotation: Periodically change secret keys
- Limited access: Grant access to keys only to necessary systems
Protection Against Attacks
- HTTPS: Always use HTTPS for transmitting webhook data
- IP whitelisting: Restrict request acceptance only to trusted Avito IP addresses
- Logging: Keep logs of all signature verifications for auditing
Performance
- Caching: If possible, cache verification results for frequently repeated requests
- 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:
- Verify the correctness of the secret key
- Ensure you’re using the original request body without modifications
- Check the signature format (should have the “sha256=” prefix)
Issue: Performance
Symptom: Signature verification takes too much time.
Solutions:
- Use more efficient cryptographic libraries
- Implement parallel processing
- Consider using hardware acceleration for cryptographic operations
Issue: Security
Symptom: Suspicions of hacking or key compromise.
Solutions:
- Immediately change the secret key
- Check logs for suspicious activity
- Increase key rotation frequency
Sources
- Avito Developer Portal - Messenger API
- HMAC Webhook Authentication: Complete Guide + Code Examples
- Webhook Signature Verification | IDaaS API Client Documentation
- Authentication & Verification | Hookdeck Event Gateway Docs
- 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:
- Algorithm: HMAC-SHA256 is used to generate the signature
- Format: Signatures always start with the “sha256=” prefix
- Verification: Requires timing-safe signature comparison to prevent timing attacks
- 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.