
Verify crypto payment callback signatures with RSA-SHA256
Verify Suawave callback signatures in Go, Node.js, PHP and C#: preserve signed bytes, fetch the RSA public key, handle rotation, and reject changed payloads.
Published , updated
To verify a Suawave webhook signature with RSA-SHA256, read the base64 x-ca-signature header and use the RSA public key from /pubkey/. Verify the exact full URL for GET callbacks or the raw body for POST callbacks. Reject invalid requests before changing an order, then validate the payment and deduplicate its UUID.
1. Identify the bytes covered by the signature
Suawave signs public payment callbacks with RSA-SHA256 using PKCS#1 v1.5 padding. The transport determines the signed message:
| Transport | Message to verify |
|---|---|
| Default GET | Full URL: external scheme, host, path and original query string |
Form POST selected with post=1 |
Raw form body, exactly as received |
JSON POST selected with json=1 |
Raw JSON body, exactly as received |
GET query ordering is part of the message. Parsing parameters into a map and serializing them again can change the bytes. For POST, whitespace or property-order changes from parsing and re-encoding JSON can also invalidate the signature.
Capture the original request target and raw body before your framework transforms them. Behind a reverse proxy, build the GET URL from a configured, trusted external origin plus the original request target. Don’t derive the origin from an untrusted Host or X-Forwarded-* header.
POST signatures cover the body; your custom callback query parameters stay in the URL. Compare the order reference and nonce with your stored order after verification, and bind the verified deposit address and coin to that order. The signature check doesn’t replace those comparisons.
2. Fetch and store the RSA public key
Call GET /pubkey/ over HTTPS:
curl "https://api.suawave.com/pubkey/"
The JSON response contains a pubkey field with a PKIX PUBLIC KEY PEM. Extract that field and store the PEM for your verifier. The key is public verification material; your handler doesn’t need the signing private key.
Require an RSA key of at least 2048 bits when accepting the key into your application. Cache it rather than fetching it for every callback. If verification fails, refresh from the configured public-key endpoint once and retry verification before rejecting the request. Suawave callbacks carry no key ID or timestamp, and rotation switches signing to the new key for retries too.
The API reference describes the public-key response and callback transport parameters.
3. Use the verifier for your language
These four functions are copied from the Suawave signature verification examples. They verify a request; they aren’t complete HTTP handlers. Pass the stored public key and your trusted external origin, preserve the raw request data, and handle a failed result before doing payment work.
Go
Pass the incoming *http.Request, the PEM bytes and your configured external origin. Callback returns an error on failure. For POST it restores the captured body so the handler can parse it after verification.
package verify
import (
"bytes"
"crypto"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"io"
"net/http"
)
func Callback(r *http.Request, publicPEM []byte, trustedOrigin string) error {
block, _ := pem.Decode(publicPEM)
if block == nil {
return errors.New("invalid public key PEM")
}
parsed, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return err
}
key, ok := parsed.(*rsa.PublicKey)
if !ok || key.N.BitLen() < 2048 {
return errors.New("invalid RSA public key")
}
var signed []byte
switch r.Method {
case http.MethodGet:
signed = []byte(trustedOrigin + r.RequestURI)
case http.MethodPost:
signed, err = io.ReadAll(io.LimitReader(r.Body, 65537))
if err != nil {
return err
}
if len(signed) > 65536 {
return errors.New("callback body too large")
}
r.Body = io.NopCloser(bytes.NewReader(signed))
default:
return errors.New("unsupported callback method")
}
signature, err := base64.StdEncoding.DecodeString(r.Header.Get("x-ca-signature"))
if err != nil {
return err
}
digest := sha256.Sum256(signed)
return rsa.VerifyPKCS1v15(key, crypto.SHA256, digest[:], signature)
}
Node.js
Pass req.originalUrl as requestUri when using Express. Capture POST input with express.raw before JSON or form parsing so rawBody is a Buffer. Read the signature header without converting its base64 representation to another encoding.
const crypto = require('crypto');
function verifyCallback({ method, requestUri, rawBody, signature }, publicKeyPem, trustedOrigin) {
let signed;
if (method === 'GET') {
signed = Buffer.from(trustedOrigin + requestUri, 'utf8');
} else if (method === 'POST') {
if (!Buffer.isBuffer(rawBody) || rawBody.length > 65536) return false;
signed = rawBody;
} else {
return false;
}
if (!signature || !/^[A-Za-z0-9+/]+={0,2}$/.test(signature)) return false;
const verifier = crypto.createVerify('RSA-SHA256');
verifier.update(signed);
return verifier.verify(publicKeyPem, signature, 'base64');
}
module.exports = { verifyCallback };
PHP
Use $_SERVER['REQUEST_URI'] for the original request target and file_get_contents('php://input') for the raw POST body. Pass the x-ca-signature header value as signatureBase64.
<?php
function verify_callback(string $method, string $requestUri, string $rawBody, string $signatureBase64, string $publicKeyPem, string $trustedOrigin): bool
{
if ($method === 'GET') {
$signed = $trustedOrigin . $requestUri;
} elseif ($method === 'POST') {
if (strlen($rawBody) > 65536) {
return false;
}
$signed = $rawBody;
} else {
return false;
}
$signature = base64_decode($signatureBase64, true);
if ($signature === false) {
return false;
}
return openssl_verify($signed, $signature, $publicKeyPem, OPENSSL_ALGO_SHA256) === 1;
}
C#
For ASP.NET Core, use GetEncodedPathAndQuery() for the encoded request target and capture the raw body bytes before model binding. Pass those values to Verify with the signature header, stored PEM and trusted origin.
using System;
using System.Security.Cryptography;
using System.Text;
public static class CallbackVerifier
{
public static bool Verify(string method, string requestUri, byte[] rawBody,
string signatureBase64, string publicKeyPem, string trustedOrigin)
{
byte[] signed;
if (method == "GET")
{
signed = Encoding.UTF8.GetBytes(trustedOrigin + requestUri);
}
else if (method == "POST" && rawBody.Length <= 65536)
{
signed = rawBody;
}
else
{
return false;
}
byte[] signature;
try
{
signature = Convert.FromBase64String(signatureBase64);
}
catch (FormatException)
{
return false;
}
using var rsa = RSA.Create();
rsa.ImportFromPem(publicKeyPem);
return rsa.VerifyData(signed, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
}
The examples reject unsupported HTTP methods and limit POST verification input to 65,536 bytes. The Go function validates the RSA key type and size itself; apply the key-validation requirement when loading the PEM for the other examples. Catch malformed-key and other verification exceptions at the HTTP handler boundary and treat them as failure, with no order updates.
4. Handle an invalid RSA-SHA256 webhook signature
If the signature doesn’t verify with the cached key, fetch the public key once and verify again. A request that still fails must receive HTTP 401 and perform no payment work. Don’t acknowledge an invalid request with *ok*.
When debugging, compare the message you passed to the verifier with the bytes received:
| Symptom | Check |
|---|---|
| GET verification fails behind a proxy | Configured external origin and original encoded request target |
| JSON POST verification fails | Whether parsing or serialization changed the raw body |
| Verification fails after a key rotation | Whether the cached PEM was refreshed once |
| Signature decoding fails | Whether the header is present and still base64 encoded |
For a controlled integration check, capture a genuine callback and verify it without running order updates. Keep the signature unchanged and alter one byte of the signed message. The changed message must fail. For GET, alter the URL or query; for POST, alter the raw body. Changing a POST query parameter alone doesn’t test body-signature integrity because the query isn’t part of that signed message.
5. Validate and record the payment after verification
A valid signature establishes the signed message’s origin and integrity. Your handler still has to decide whether the deposit pays the order.
Compare the stored nonce and order reference with the callback query. Check address_in, coin and the confirmed amount against the stored order. Preserve amounts as decimal strings until converting them with exact arithmetic.
Record the event UUID durably with the resulting order change. Retried deliveries reuse the UUID, so an already processed event mustn’t trigger another fulfillment. Pending and confirmed callbacks have different UUIDs; never let a late pending callback undo a confirmed state.
Fulfill only on pending equal to "0", once your amount policy is satisfied. Then respond with HTTP 200 and the plain body *ok* within 30 seconds. The callback guide documents retries, acknowledgement and the event fields.
Common verification questions
Does a valid signature prevent a replay?
The signature alone doesn’t establish freshness. Public callbacks have no timestamp, and a captured signed message can still pass verification. Use durable UUID deduplication and order-state checks so processing the same event again doesn’t repeat its effects.
Should the handler sort GET query parameters?
No. Verify the exact original query string. The sender appends its fields to your callback URL, and the signature covers the resulting full URL. Reconstructing that query from parsed values risks changing its ordering or encoding.
Should the handler verify parsed JSON?
No. Verify the raw POST body first, then parse it. The Node.js function requires a Buffer for that reason. Keep the same sequence for form POST: verify its raw body before interpreting the fields.
Is signature verification enough to mark an order paid?
No. Match the verified deposit to the stored order, deduplicate the UUID and evaluate the confirmed amount. A genuine pending callback is still a pending event. A genuine confirmed deposit can still be smaller than the order total.