# Verify Webhook Signatures > **WARNING** >**Critical Security Step!** Always verify webhook signatures to ensure requests actually came from CryptAPI and haven't been tampered with. This prevents malicious actors from sending fake webhooks to your application. CryptAPI uses a **1024-bit RSA SHA256 signature** with a public-key signature scheme to sign every webhook sent to your service. This ensures all data was sent from CryptAPI and can be trusted. ## How CryptAPI Signature Works ### What Gets Signed - **For GET requests**: The full URL including all query parameters is signed - **For POST requests**: The entire request body is signed ### Signature Details - **Algorithm**: RSA SHA256 with PKCS1v15 padding - **Key Size**: 1024-bit RSA key - **Header**: Signature is sent in the `x-ca-signature` header - **Encoding**: Signature is base64-encoded - **Public Key**: Available at `https://api.cryptapi.io/pubkey/` ### Example Signed Data For a GET request, the signed data looks like: ```bash https://yoursite.com/webhook?uuid=dbfcb40e-5a6b-4305-9fa2-b0fbda6e3ff2&address_in=3PFoGK63cVVUWnd2vu7W1kM83NXUfvzMqM&txid_in=a2174ffd39289100709f2a07b129cdbba69df2e22e5be1830221dab1fd4e332c&value_coin=0.05&confirmations=3&pending=0 ``` For a POST request, the signed data is the raw request body: ```bash uuid=dbfcb40e-5a6b-4305-9fa2-b0fbda6e3ff2&address_in=3PFoGK63cVVUWnd2vu7W1kM83NXUfvzMqM&txid_in=a2174ffd39289100709f2a07b129cdbba69df2e22e5be1830221dab1fd4e332c&value_coin=0.05&confirmations=3&pending=0 ``` ## Implementation Examples ```javascript // Node.js verification const crypto = require('crypto'); // CryptAPI's public key (you can also fetch from https://api.cryptapi.io/pubkey/) const CRYPTAPI_PUBLIC_KEY = `-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3FT0Ym8b3myVxhQW7ESuuu6lo dGAsUJs4fq+Ey//jm27jQ7HHHDmP1YJO7XE7Jf/0DTEJgcw4EZhJFVwsk6d3+4fy Bsn0tKeyGMiaE6cVkX0cy6Y85o8zgc/CwZKc0uw6d5siAo++xl2zl+RGMXCELQVE ox7pp208zTvown577wIDAQAB -----END PUBLIC KEY-----`; function verifyCryptAPISignature(req) { try { // Get signature from header const signature_b64 = req.headers['x-ca-signature']; if (!signature_b64) { console.error('Missing x-ca-signature header'); return false; } // Decode signature from base64 const signature = Buffer.from(signature_b64, 'base64'); // Determine what data to verify based on request method let dataToVerify; if (req.method === 'GET') { // For GET requests, sign the full URL dataToVerify = req.protocol + '://' + req.get('host') + req.originalUrl; } else { // For POST requests, sign the raw body dataToVerify = req.rawBody; // You need raw body middleware } // Create verifier and verify signature const verifier = crypto.createVerify('RSA-SHA256'); verifier.update(dataToVerify); const isValid = verifier.verify(CRYPTAPI_PUBLIC_KEY, signature); if (!isValid) { console.error('Invalid signature'); } return isValid; } catch (error) { console.error('Signature verification error:', error); return false; } } // Express middleware to capture raw body function captureRawBody(req, res, next) { req.rawBody = ''; req.on('data', chunk => { req.rawBody += chunk.toString(); }); req.on('end', () => { next(); }); } // Usage in Express app.use('/webhook', captureRawBody); app.post('/webhook', (req, res) => { if (!verifyCryptAPISignature(req)) { return res.status(401).send('Invalid signature'); } // Process webhook safely console.log('Verified webhook received'); res.status(200).send('*ok*'); }); ``` ```python import base64 from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend # CryptAPI's public key CRYPTAPI_PUBLIC_KEY = """-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3FT0Ym8b3myVxhQW7ESuuu6lo dGAsUJs4fq+Ey//jm27jQ7HHHDmP1YJO7XE7Jf/0DTEJgcw4EZhJFVwsk6d3+4fy Bsn0tKeyGMiaE6cVkX0cy6Y85o8zgc/CwZKc0uw6d5siAo++xl2zl+RGMXCELQVE ox7pp208zTvown577wIDAQAB -----END PUBLIC KEY-----""" def verify_cryptapi_signature(request): """ Verify CryptAPI webhook signature Args: request: Django HttpRequest or Flask request object Returns: bool: True if signature is valid, False otherwise """ try: # Get signature from header signature_b64 = request.headers.get('x-ca-signature') if not signature_b64: print("Missing x-ca-signature header") return False # Determine what data to verify if request.method == 'GET': # For GET requests, sign the full URL if hasattr(request, 'build_absolute_uri'): # Django data_to_verify = request.build_absolute_uri() else: # Flask data_to_verify = request.url else: # For POST requests, sign the raw body if hasattr(request, 'body'): # Django data_to_verify = request.body.decode('utf-8') else: # Flask data_to_verify = request.get_data(as_text=True) # Load public key public_key = serialization.load_pem_public_key( CRYPTAPI_PUBLIC_KEY.encode('utf-8'), backend=default_backend() ) # Decode signature signature = base64.b64decode(signature_b64) # Verify signature public_key.verify( signature, data_to_verify.encode('utf-8'), padding.PKCS1v15(), hashes.SHA256() ) return True except Exception as e: print(f"Signature verification error: {e}") return False # Django usage def cryptapi_webhook(request): if not verify_cryptapi_signature(request): return HttpResponse('Invalid signature', status=401) # Process webhook safely print("Verified webhook received") return HttpResponse('*ok*') # Flask usage @app.route('/webhook', methods=['GET', 'POST']) def cryptapi_webhook(): if not verify_cryptapi_signature(request): return 'Invalid signature', 401 # Process webhook safely print("Verified webhook received") return '*ok*' ``` ```php getMessage()); return false; } } // Usage if (!verifyCryptAPISignature()) { http_response_code(401); exit('Invalid signature'); } // Process webhook safely error_log('Verified webhook received'); http_response_code(200); echo '*ok*'; ?> ``` ```ruby require 'openssl' # CryptAPI's public key (you can also fetch it from https://api.cryptapi.io/pubkey/) CRYPTAPI_PUBLIC_KEY = OpenSSL::PKey::RSA.new(<<~PEM) -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3FT0Ym8b3myVxhQW7ESuuu6lo dGAsUJs4fq+Ey//jm27jQ7HHHDmP1YJO7XE7Jf/0DTEJgcw4EZhJFVwsk6d3+4fy Bsn0tKeyGMiaE6cVkX0cy6Y85o8zgc/CwZKc0uw6d5siAo++xl2zl+RGMXCELQVE ox7pp208zTvown577wIDAQAB -----END PUBLIC KEY----- PEM # Works with Rails and Sinatra requests. Pass the raw body you read from the request. def verify_cryptapi_signature(request, raw_body) signature_b64 = request.env['HTTP_X_CA_SIGNATURE'] return false if signature_b64.nil? || signature_b64.empty? # For GET requests, sign the full URL. For POST requests, sign the raw body. data = request.get? ? "https://#{request.host_with_port}#{request.fullpath}" : raw_body CRYPTAPI_PUBLIC_KEY.verify(OpenSSL::Digest.new('SHA256'), signature_b64.unpack1('m'), data) rescue OpenSSL::PKey::PKeyError => e warn "Signature verification error: #{e.message}" false end # Rails usage (route both GET and POST to this action) class WebhooksController < ActionController::API def receive unless verify_cryptapi_signature(request, request.raw_post) return render plain: 'Invalid signature', status: :unauthorized end # Process webhook safely render plain: '*ok*' end end ``` ```csharp using System.Security.Cryptography; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; public static class CryptAPISignature { // CryptAPI's public key (you can also fetch it from https://api.cryptapi.io/pubkey/) private const string PublicKeyPem = @"-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3FT0Ym8b3myVxhQW7ESuuu6lo dGAsUJs4fq+Ey//jm27jQ7HHHDmP1YJO7XE7Jf/0DTEJgcw4EZhJFVwsk6d3+4fy Bsn0tKeyGMiaE6cVkX0cy6Y85o8zgc/CwZKc0uw6d5siAo++xl2zl+RGMXCELQVE ox7pp208zTvown577wIDAQAB -----END PUBLIC KEY-----"; // Pass the raw body you read from the request public static bool Verify(HttpRequest request, string rawBody) { var signatureB64 = request.Headers["x-ca-signature"].ToString(); if (string.IsNullOrEmpty(signatureB64)) return false; // For GET requests, sign the full URL. For POST requests, sign the raw body. var data = HttpMethods.IsGet(request.Method) ? $"https://{request.Host}{request.Path}{request.QueryString}" : rawBody; try { using var rsa = RSA.Create(); rsa.ImportFromPem(PublicKeyPem); return rsa.VerifyData( Encoding.UTF8.GetBytes(data), Convert.FromBase64String(signatureB64), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); } catch (Exception e) when (e is FormatException or CryptographicException) { return false; } } } // ASP.NET Core usage [ApiController] public class WebhookController : ControllerBase { [AcceptVerbs("GET", "POST", Route = "webhook")] public async Task Webhook() { using var reader = new StreamReader(Request.Body); var rawBody = await reader.ReadToEndAsync(); if (!CryptAPISignature.Verify(Request, rawBody)) return Unauthorized("Invalid signature"); // Process webhook safely return Content("*ok*"); } } ``` ```java import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; public final class CryptAPISignature { // CryptAPI's public key (you can also fetch it from https://api.cryptapi.io/pubkey/) private static final String PUBLIC_KEY_PEM = """ -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3FT0Ym8b3myVxhQW7ESuuu6lo dGAsUJs4fq+Ey//jm27jQ7HHHDmP1YJO7XE7Jf/0DTEJgcw4EZhJFVwsk6d3+4fy Bsn0tKeyGMiaE6cVkX0cy6Y85o8zgc/CwZKc0uw6d5siAo++xl2zl+RGMXCELQVE ox7pp208zTvown577wIDAQAB -----END PUBLIC KEY----- """; private static final PublicKey PUBLIC_KEY = loadPublicKey(); private static PublicKey loadPublicKey() { try { String base64 = PUBLIC_KEY_PEM .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", "") .replaceAll("\\s", ""); byte[] der = Base64.getDecoder().decode(base64); return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(der)); } catch (Exception e) { throw new IllegalStateException("Can't load the CryptAPI public key", e); } } // Pass the raw body you read from the request public static boolean verify(HttpServletRequest request, String rawBody) { String signatureB64 = request.getHeader("x-ca-signature"); if (signatureB64 == null || signatureB64.isEmpty()) { return false; } // For GET requests, sign the full URL. For POST requests, sign the raw body. String data; if ("GET".equals(request.getMethod())) { String query = request.getQueryString(); data = "https://" + request.getHeader("Host") + request.getRequestURI() + (query != null ? "?" + query : ""); } else { data = rawBody; } try { Signature verifier = Signature.getInstance("SHA256withRSA"); verifier.initVerify(PUBLIC_KEY); verifier.update(data.getBytes(StandardCharsets.UTF_8)); return verifier.verify(Base64.getDecoder().decode(signatureB64)); } catch (Exception e) { return false; } } } // Spring Boot usage @RestController public class WebhookController { @RequestMapping(value = "/webhook", method = {RequestMethod.GET, RequestMethod.POST}) public ResponseEntity webhook(HttpServletRequest request) throws IOException { // Read the raw body before anything calls request.getParameter() String rawBody = new String(request.getInputStream().readAllBytes(), StandardCharsets.UTF_8); if (!CryptAPISignature.verify(request, rawBody)) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid signature"); } // Process webhook safely return ResponseEntity.ok("*ok*"); } } ``` ```go package main import ( "crypto" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/pem" "io" "log" "net/http" ) // CryptAPI's public key (you can also fetch it from https://api.cryptapi.io/pubkey/) const cryptapiPublicKeyPEM = `-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3FT0Ym8b3myVxhQW7ESuuu6lo dGAsUJs4fq+Ey//jm27jQ7HHHDmP1YJO7XE7Jf/0DTEJgcw4EZhJFVwsk6d3+4fy Bsn0tKeyGMiaE6cVkX0cy6Y85o8zgc/CwZKc0uw6d5siAo++xl2zl+RGMXCELQVE ox7pp208zTvown577wIDAQAB -----END PUBLIC KEY-----` var cryptapiPublicKey = mustLoadPublicKey() func mustLoadPublicKey() *rsa.PublicKey { block, _ := pem.Decode([]byte(cryptapiPublicKeyPEM)) if block == nil { log.Fatal("can't decode the CryptAPI public key") } key, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { log.Fatal(err) } return key.(*rsa.PublicKey) } // Pass the raw body you read from the request func verifyCryptAPISignature(r *http.Request, body []byte) bool { signature, err := base64.StdEncoding.DecodeString(r.Header.Get("x-ca-signature")) if err != nil || len(signature) == 0 { return false } // For GET requests, sign the full URL. For POST requests, sign the raw body. data := body if r.Method == http.MethodGet { data = []byte("https://" + r.Host + r.RequestURI) } hash := sha256.Sum256(data) return rsa.VerifyPKCS1v15(cryptapiPublicKey, crypto.SHA256, hash[:], signature) == nil } func webhookHandler(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "Bad request", http.StatusBadRequest) return } if !verifyCryptAPISignature(r, body) { http.Error(w, "Invalid signature", http.StatusUnauthorized) return } // Process webhook safely log.Println("Verified webhook received") w.Write([]byte("*ok*")) } func main() { http.HandleFunc("/webhook", webhookHandler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` > **INFO** >**Read the raw body before you parse it.** CryptAPI signs the exact bytes it sends. If a framework parses the body first, the bytes you check may differ, and the check fails. For GET requests, the URL you rebuild must match the `callback` URL CryptAPI called, scheme and host included. Behind a proxy, rebuild it from the public HTTPS address. > **TIP** >**Test signature verification!** Make sure to test the signature verification when testing your integration as it's a very important safety feature. ## Security Best Practices 1. **Always verify signatures** - Never skip signature verification in production 2. **Use HTTPS** - Ensure your webhook endpoint uses HTTPS 3. **Implement rate limiting** - Prevent abuse of your webhook endpoint 4. **Log security events** - Log all signature verification failures 5. **Validate webhook data** - Even verified webhooks should have data validation 6. **Use idempotency** - Prevent duplicate processing of webhooks > **SUCCESS** >**Signature Verification Complete!** Your webhook endpoint is now secure and can trust that all requests come from CryptAPI. Remember to test thoroughly and monitor for any verification failures.