Sample code for 30+ languages & platforms
Android™ Requires Chilkat v11.5.0+

Box: Verify a Captured V2 Webhook Signature

See more Box Examples

Verify raw payload bytes and captured headers using the configured primary and secondary signing keys. The example rejects stale/future timestamps and compares randomized HMACs of the signatures to avoid exposing a signature-prefix timing comparison. It does not host an HTTP listener. The receiver must persist/deduplicate the verified event and acknowledge promptly.

See the Box API guide for setup and the complete workflow.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    //  Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
    //  See Global Unlock Sample.
    //  Guide: Box API Guide.

    success = false;

    //  Save the exact HTTP body bytes to this file, without JSON reserialization.
    CkBinData rawBody = new CkBinData();
    success = rawBody.LoadFile("qa_data/box_webhook_body.bin");
    if (success != true) {
        Log.i(TAG, rawBody.lastErrorText());
        return;
        }

    //  Read these fields case-insensitively from the incoming request headers.
    //  For this offline example, enter the captured header values.
    String timestamp = "BOX_DELIVERY_TIMESTAMP";
    String primarySignature = "BOX_SIGNATURE_PRIMARY";
    String secondarySignature = "BOX_SIGNATURE_SECONDARY";
    String signatureVersion = "1";
    String signatureAlgorithm = "HmacSHA256";
    //  Retrieve configured keys from protected application configuration.
    String primaryKey = "BOX_PRIMARY_SIGNATURE_KEY";
    String secondaryKey = "BOX_SECONDARY_SIGNATURE_KEY";
    if ((signatureVersion != "1") or (signatureAlgorithm != "HmacSHA256")) {
        Log.i(TAG, "Unsupported signature version or algorithm.");
        return;
        }

    CkDateTime delivered = new CkDateTime();
    success = delivered.SetFromTimestamp(timestamp);
    if (success != true) {
        Log.i(TAG, delivered.lastErrorText());
        return;
        }

    CkDateTime now = new CkDateTime();
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        Log.i(TAG, now.lastErrorText());
        return;
        }

    int age = Integer.toString(now.GetAsUnixTime(false)) - Integer.toString(delivered.GetAsUnixTime(false));
    //  Box recommends rejecting deliveries older than ten minutes.
    //  Allow at most 60 seconds of future clock skew; keep the server clock synchronized.
    if ((age > 600) or (age < -60)) {
        Log.i(TAG, "Delivery timestamp is outside the accepted window.");
        return;
        }

    CkBinData signedBytes = new CkBinData();
    success = signedBytes.AppendBd(rawBody);
    if (success != true) {
        Log.i(TAG, signedBytes.lastErrorText());
        return;
        }

    success = signedBytes.AppendString(timestamp,"utf-8");
    if (success != true) {
        Log.i(TAG, signedBytes.lastErrorText());
        return;
        }

    CkCrypt2 mac = new CkCrypt2();
    mac.put_MacAlgorithm("hmac");
    mac.put_HashAlgorithm("sha256");
    mac.put_EncodingMode("base64");
    success = mac.SetMacKeyString(primaryKey);
    if (success != true) {
        Log.i(TAG, mac.lastErrorText());
        return;
        }

    String expectedPrimary = mac.macBdENC(signedBytes);
    if (mac.get_LastMethodSuccess() != true) {
        Log.i(TAG, mac.lastErrorText());
        return;
        }

    success = mac.SetMacKeyString(secondaryKey);
    if (success != true) {
        Log.i(TAG, mac.lastErrorText());
        return;
        }

    String expectedSecondary = mac.macBdENC(signedBytes);
    if (mac.get_LastMethodSuccess() != true) {
        Log.i(TAG, mac.lastErrorText());
        return;
        }

    //  Blind both sides with a fresh secret random key before equality comparison.
    //  Never compare the original HMAC strings using a prefix-short-circuit comparison.
    //  A host-language receiver can instead use its standard constant-time byte comparison.
    CkPrng random = new CkPrng();
    String comparisonKey = random.genRandom(32,"base64");
    if (random.get_LastMethodSuccess() != true) {
        Log.i(TAG, random.lastErrorText());
        return;
        }

    success = mac.SetMacKeyEncoded(comparisonKey,"base64");
    if (success != true) {
        Log.i(TAG, mac.lastErrorText());
        return;
        }

    String pExpected = mac.macStringENC(expectedPrimary);
    if (mac.get_LastMethodSuccess() != true) {
        Log.i(TAG, mac.lastErrorText());
        return;
        }

    String pReceived = mac.macStringENC(primarySignature);
    if (mac.get_LastMethodSuccess() != true) {
        Log.i(TAG, mac.lastErrorText());
        return;
        }

    String sExpected = mac.macStringENC(expectedSecondary);
    if (mac.get_LastMethodSuccess() != true) {
        Log.i(TAG, mac.lastErrorText());
        return;
        }

    String sReceived = mac.macStringENC(secondarySignature);
    if (mac.get_LastMethodSuccess() != true) {
        Log.i(TAG, mac.lastErrorText());
        return;
        }

    boolean validPrimary = (primaryKey != "") and (primarySignature != "") and (pExpected == pReceived);
    boolean validSecondary = (secondaryKey != "") and (secondarySignature != "") and (sExpected == sReceived);
    if ((validPrimary == false) and (validSecondary == false)) {
        Log.i(TAG, "Signature verification failed.");
        return;
        }

    //  Parse JSON only after signature verification.
    CkJsonObject webhookEvent = new CkJsonObject();
    success = webhookEvent.Load(rawBody.getString("utf-8"));
    if (success != true) {
        Log.i(TAG, webhookEvent.lastErrorText());
        return;
        }

    Log.i(TAG, "Verified event ID: " + webhookEvent.stringOf("id"));
    Log.i(TAG, "Trigger: " + webhookEvent.stringOf("trigger"));
    //  Deduplicate using event.id, not BOX-DELIVERY-ID, which changes on retries.
    //  Verify the target belongs to your configured webhook before dispatching work.

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}