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

Amazon SNS: Verify HTTPS Notifications and Detect Batch Duplicates

See more Amazon SNS Examples

Verify an SNS HTTPS delivery envelope before processing it. Delivery signatures use RSA, not the SigV4 used to call the SNS API.

Reads a private file shaped as {"messages":[SNS-envelope,...]}. Verifies Notifications and both confirmation types, including optional Subject, exact LF canonicalization, RSA/SHA-256 signature version 2, and SHA-1 version 1 compatibility. It pins an expected topic and regional HTTPS certificate source, disallows redirects and unusual certificate paths, validates chain signatures/root trust/validity dates, and checks a configurable timestamp window. Provision required intermediates and approved roots; never accept roots from an incoming envelope. The checks are not an online certificate-revocation service or a general-purpose PKIX policy engine.

Duplicate detection uses (TopicArn, MessageId) and lasts only within this batch; the example performs no business side effects. For an HTTP receiver, enforce request-size limits before JSON parsing, persist a unique inbox key and accepted payload transactionally, acknowledge only durable acceptance, and process idempotently. Choose timestamp retention to cover the intended delivery/replay window; the illustrative 24-hour bound may reject deliberately replayed old messages. Confirm only subscriptions the application requested, using the verified Token and a configured API endpoint; it never follows SubscribeURL or automatically resubscribes.

AWS signature verification guidance

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;

    CkStringBuilder stringCompare = new CkStringBuilder();
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  File format: {"messages":[<SNS envelope>, ...]}. Do not store untrusted files publicly.

    CkJsonObject batch = new CkJsonObject();
    batch.put_Strict(true);
    success = batch.LoadFile("qa_data/aws/sns_notifications.json");
    if (success != true) {
        Log.i(TAG, "Could not parse notification envelopes.");
        return;
        }

    if (batch.JsonTypeOf("messages") != 4) {
        Log.i(TAG, "Expected a messages array.");
        return;
        }

    int count = batch.SizeOfArray("messages");
    if ((count < 1) or (count > 100)) {
        Log.i(TAG, "Use 1 to 100 envelopes per verification batch.");
        return;
        }

    String allowedTopic = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example";
    String certPrefix = "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-";
    //  Pin the expected topic and matching regional SNS host in application configuration.
    CkHashtable seenMessages = new CkHashtable();
    CkJsonObject envelope = new CkJsonObject();
    CkDateTime now = new CkDateTime();
    success = now.SetFromCurrentSystemTime();
    if (success != true) {
        Log.i(TAG, "Could not read current time.");
        return;
        }

    int envelopeIndex = 0;
    while ((envelopeIndex < count)) {
        batch.put_I(envelopeIndex);
        success = batch.ObjectOf2("messages[i]",envelope);
        if (success != true) {
            Log.i(TAG, "Expected a JSON object envelope.");
            return;
            }

        CkHashtable fieldNames = new CkHashtable();
        int fieldIndex = 0;
        while ((fieldIndex < envelope.get_Size())) {
            String fieldName = envelope.nameAt(fieldIndex);
            if (fieldNames.Contains(fieldName) == true) {
                Log.i(TAG, "Duplicate envelope field.");
                return;
                }

            success = fieldNames.AddStr(fieldName,"seen");
            if (success != true) {
                Log.i(TAG, "Could not track envelope fields.");
                return;
                }

            fieldIndex = fieldIndex + 1;
            }

        stringCompare.SetString(envelope.stringOf("Type"));
        boolean stringMatch1 = stringCompare.ContentsEqual("",true);
        if ((envelope.JsonTypeOf("Type") != 1) or (stringMatch1 == true)) {
            Log.i(TAG, "Missing or invalid Type.");
            return;
            }

        stringCompare.SetString(envelope.stringOf("MessageId"));
        boolean stringMatch2 = stringCompare.ContentsEqual("",true);
        if ((envelope.JsonTypeOf("MessageId") != 1) or (stringMatch2 == true)) {
            Log.i(TAG, "Missing or invalid MessageId.");
            return;
            }

        stringCompare.SetString(envelope.stringOf("Message"));
        boolean stringMatch3 = stringCompare.ContentsEqual("",true);
        if ((envelope.JsonTypeOf("Message") != 1) or (stringMatch3 == true)) {
            Log.i(TAG, "Missing or invalid Message.");
            return;
            }

        stringCompare.SetString(envelope.stringOf("Timestamp"));
        boolean stringMatch4 = stringCompare.ContentsEqual("",true);
        if ((envelope.JsonTypeOf("Timestamp") != 1) or (stringMatch4 == true)) {
            Log.i(TAG, "Missing or invalid Timestamp.");
            return;
            }

        stringCompare.SetString(envelope.stringOf("TopicArn"));
        boolean stringMatch5 = stringCompare.ContentsEqual("",true);
        if ((envelope.JsonTypeOf("TopicArn") != 1) or (stringMatch5 == true)) {
            Log.i(TAG, "Missing or invalid TopicArn.");
            return;
            }

        stringCompare.SetString(envelope.stringOf("SignatureVersion"));
        boolean stringMatch6 = stringCompare.ContentsEqual("",true);
        if ((envelope.JsonTypeOf("SignatureVersion") != 1) or (stringMatch6 == true)) {
            Log.i(TAG, "Missing or invalid SignatureVersion.");
            return;
            }

        stringCompare.SetString(envelope.stringOf("Signature"));
        boolean stringMatch7 = stringCompare.ContentsEqual("",true);
        if ((envelope.JsonTypeOf("Signature") != 1) or (stringMatch7 == true)) {
            Log.i(TAG, "Missing or invalid Signature.");
            return;
            }

        stringCompare.SetString(envelope.stringOf("SigningCertURL"));
        boolean stringMatch8 = stringCompare.ContentsEqual("",true);
        if ((envelope.JsonTypeOf("SigningCertURL") != 1) or (stringMatch8 == true)) {
            Log.i(TAG, "Missing or invalid SigningCertURL.");
            return;
            }

        String messageType = envelope.stringOf("Type");
        stringCompare.SetString(messageType);
        boolean stringMatch9 = stringCompare.ContentsEqual("Notification",true);
        stringCompare.SetString(messageType);
        boolean stringMatch10 = stringCompare.ContentsEqual("SubscriptionConfirmation",true);
        stringCompare.SetString(messageType);
        boolean stringMatch11 = stringCompare.ContentsEqual("UnsubscribeConfirmation",true);
        if ((stringMatch9 != true) and (stringMatch10 != true) and (stringMatch11 != true)) {
            Log.i(TAG, "Unsupported SNS message type.");
            return;
            }

        stringCompare.SetString(envelope.stringOf("TopicArn"));
        boolean stringMatch12 = stringCompare.ContentsEqual(allowedTopic,true);
        if (stringMatch12 != true) {
            Log.i(TAG, "Unexpected SNS topic.");
            return;
            }

        String signatureVersion = envelope.stringOf("SignatureVersion");
        stringCompare.SetString(signatureVersion);
        boolean stringMatch13 = stringCompare.ContentsEqual("1",true);
        stringCompare.SetString(signatureVersion);
        boolean stringMatch14 = stringCompare.ContentsEqual("2",true);
        if ((stringMatch13 != true) and (stringMatch14 != true)) {
            Log.i(TAG, "Unsupported delivery signature version.");
            return;
            }

        String hashAlgorithm = "sha256";
        stringCompare.SetString(signatureVersion);
        boolean stringMatch15 = stringCompare.ContentsEqual("1",true);
        if (stringMatch15 == true) {
            hashAlgorithm = "sha1";
            }

        stringCompare.SetString(messageType);
        boolean stringMatch16 = stringCompare.ContentsEqual("Notification",true);
        if (stringMatch16 != true) {
            stringCompare.SetString(envelope.stringOf("SubscribeURL"));
            boolean stringMatch17 = stringCompare.ContentsEqual("",true);
            stringCompare.SetString(envelope.stringOf("Token"));
            boolean stringMatch18 = stringCompare.ContentsEqual("",true);
            if ((envelope.JsonTypeOf("SubscribeURL") != 1) or (stringMatch17 == true) or (envelope.JsonTypeOf("Token") != 1) or (stringMatch18 == true)) {
                Log.i(TAG, "Confirmation envelope is missing fields.");
                return;
                }

            }

        if (envelope.HasMember("Subject") == true) {
            if (envelope.JsonTypeOf("Subject") != 1) {
                Log.i(TAG, "Subject must be a string when present.");
                return;
                }

            }

        CkDateTime timestamp = new CkDateTime();
        success = timestamp.SetFromTimestamp(envelope.stringOf("Timestamp"));
        if (success != true) {
            Log.i(TAG, "Invalid notification timestamp.");
            return;
            }

        int ageSeconds = now.DiffSeconds(timestamp);
        if ((ageSeconds < -300) or (ageSeconds > 86400)) {
            Log.i(TAG, "Notification outside the configured 24-hour age / 5-minute clock-skew window.");
            return;
            }

        CkStringBuilder certUrl = new CkStringBuilder();
        certUrl.Append(envelope.stringOf("SigningCertURL"));
        CkStringBuilder prefix = new CkStringBuilder();
        prefix.Append(certPrefix);
        if ((certUrl.StartsWith(certPrefix,true) != true) or (certUrl.EndsWith(".pem",true) != true) or (certUrl.get_Length() <= prefix.get_Length() + 4)) {
            Log.i(TAG, "Untrusted signing-certificate URL.");
            return;
            }

        //  Only a flat SNS certificate filename is allowed: no query, fragment, escapes,
        //  userinfo, alternate port, path traversal, or redirect destination.
        CkStringBuilder filenameChars = new CkStringBuilder();
        filenameChars.Append("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_");
        int charIndex = prefix.get_Length();
        while ((charIndex < certUrl.get_Length() - 4)) {
            if (filenameChars.Contains(certUrl.getRange(charIndex,1,false),true) != true) {
                Log.i(TAG, "Invalid signing-certificate filename.");
                return;
                }

            charIndex = charIndex + 1;
            }

        CkHttp http = new CkHttp();
        http.put_RequireSslCertVerify(true);
        http.put_FollowRedirects(false);
        http.put_ConnectTimeout(20);
        http.put_ReadTimeout(30);
        int maxCertBytes = 65536;
        http.put_MaxResponseSize(maxCertBytes);
        http.put_VerboseLogging(false);
        String certPem = http.quickGetStr(certUrl.getAsString());
        if ((http.get_LastMethodSuccess() != true) or (http.get_LastStatus() != 200)) {
            Log.i(TAG, "Could not retrieve the certificate securely from the pinned SNS endpoint.");
            return;
            }

        CkCert signingCert = new CkCert();
        success = signingCert.LoadPem(certPem);
        if (success != true) {
            Log.i(TAG, "Invalid signing certificate.");
            return;
            }

        CkCertChain chain = new CkCertChain();
        success = signingCert.BuildCertChain(chain);
        if (success != true) {
            Log.i(TAG, "Could not build signing-certificate chain.");
            return;
            }

        if (chain.get_ReachesRoot() != true) {
            Log.i(TAG, "Incomplete signing-certificate chain; provision trusted intermediates.");
            return;
            }

        CkTrustedRoots roots = new CkTrustedRoots();
        roots.put_TrustSystemCaRoots(true);
        if (chain.IsRootTrusted(roots) != true) {
            Log.i(TAG, "Untrusted signing-certificate root.");
            return;
            }

        success = chain.VerifyCertSignatures();
        if (success != true) {
            Log.i(TAG, "Invalid certificate-chain signatures.");
            return;
            }

        int certIndex = 0;
        CkCert chainCert = new CkCert();
        while ((certIndex < chain.get_NumCerts())) {
            success = chain.CertAt(certIndex,chainCert);
            if (success != true) {
                Log.i(TAG, "Could not read chain certificate.");
                return;
                }

            CkDateTime validFrom = new CkDateTime();
            CkDateTime validTo = new CkDateTime();
            success = validFrom.SetFromRfc822(chainCert.validFromStr());
            if (success != true) {
                Log.i(TAG, "Invalid certificate validity start.");
                return;
                }

            success = validTo.SetFromRfc822(chainCert.validToStr());
            if (success != true) {
                Log.i(TAG, "Invalid certificate validity end.");
                return;
                }

            if ((now.DiffSeconds(validFrom) < 0) or (now.DiffSeconds(validTo) > 0)) {
                Log.i(TAG, "Certificate outside its validity period.");
                return;
                }

            certIndex = certIndex + 1;
            }

        CkStringBuilder canonical = new CkStringBuilder();
        canonical.AppendLine("Message",false);
        canonical.AppendLine(envelope.stringOf("Message"),false);
        canonical.AppendLine("MessageId",false);
        canonical.AppendLine(envelope.stringOf("MessageId"),false);
        stringCompare.SetString(messageType);
        boolean stringMatch19 = stringCompare.ContentsEqual("Notification",true);
        if (stringMatch19 == true) {
            if (envelope.HasMember("Subject") == true) {
                canonical.AppendLine("Subject",false);
                canonical.AppendLine(envelope.stringOf("Subject"),false);
                }

            }
        else {
            canonical.AppendLine("SubscribeURL",false);
            canonical.AppendLine(envelope.stringOf("SubscribeURL"),false);
            }

        canonical.AppendLine("Timestamp",false);
        canonical.AppendLine(envelope.stringOf("Timestamp"),false);
        stringCompare.SetString(messageType);
        boolean stringMatch20 = stringCompare.ContentsEqual("Notification",true);
        if (stringMatch20 != true) {
            canonical.AppendLine("Token",false);
            canonical.AppendLine(envelope.stringOf("Token"),false);
            }

        canonical.AppendLine("TopicArn",false);
        canonical.AppendLine(envelope.stringOf("TopicArn"),false);
        canonical.AppendLine("Type",false);
        canonical.AppendLine(envelope.stringOf("Type"),false);
        CkPublicKey publicKey = new CkPublicKey();
        success = signingCert.GetPublicKey(publicKey);
        if (success != true) {
            Log.i(TAG, "Could not extract signing public key.");
            return;
            }

        CkRsa rsa = new CkRsa();
        rsa.put_Charset("utf-8");
        rsa.put_EncodingMode("base64");
        rsa.put_LittleEndian(false);
        success = rsa.UsePublicKey(publicKey);
        if (success != true) {
            Log.i(TAG, "Could not configure verification key.");
            return;
            }

        success = rsa.VerifyStringENC(canonical.getAsString(),hashAlgorithm,envelope.stringOf("Signature"));
        if (success != true) {
            Log.i(TAG, "SNS delivery signature is invalid.");
            return;
            }

        //  Use a JSON-encoded composite key to avoid ambiguous concatenation.
        CkJsonObject identity = new CkJsonObject();
        success = identity.UpdateString("topic",allowedTopic);
        if (success != true) {
            Log.i(TAG, "Could not form duplicate key.");
            return;
            }

        success = identity.UpdateString("id",envelope.stringOf("MessageId"));
        if (success != true) {
            Log.i(TAG, "Could not form duplicate key.");
            return;
            }

        String duplicateKey = identity.emit();
        if (seenMessages.Contains(duplicateKey) == true) {
            Log.i(TAG, "Verified duplicate skipped: " + envelope.stringOf("MessageId"));
            }
        else {
            success = seenMessages.AddStr(duplicateKey,"verified");
            if (success != true) {
                Log.i(TAG, "Could not track duplicate key.");
                return;
                }

            Log.i(TAG, "Verified " + messageType + " / " + envelope.stringOf("MessageId"));
            //  Notification: durably enqueue/process only after verification.
            //  SubscriptionConfirmation: submit the verified Token to the configured SNS
            //  endpoint only if this is a subscription your application requested.
            //  UnsubscribeConfirmation: record status; do not automatically resubscribe.
            //  Never follow SubscribeURL merely because it appeared in an envelope.
            }

        envelopeIndex = envelopeIndex + 1;
        }

    Log.i(TAG, "All envelopes verified; duplicate detection was limited to this batch.");

  }

  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."
  }
}