📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📰 Signing and Encrypting Payment Payloads in C#: Lessons from a Cross-Border Remittance System

Signing and Encrypting Payment Payloads in C#: Lessons from a Cross-Border Remittance System

When you build a system that moves money between countries, "it works" isn't the bar. The bar is: can anyone read this message on the way? Can anyone change it? And if something goes wrong, can we prove who sent what?

From 2023 to 2024 I worked as a Senior .NET Developer at Fintech Solutions in Kathmandu, where I led two remittance products: iSend Remit, our own in-house product, and BNB Remit, which we built for Bhutan National Bank. Both were fintech solutions for remittance and secure cross-border payments, and a big part of the work was securing transactions with encryption and digital signatures.

iSend Remit is a cross-border remittance app for sending money to family, friends and business contacts overseas. BNB Remit is Bhutan National Bank's app for sending money from Australia to Bhutan, run with its Australian partner TransCash International. Money goes straight into the receiver's account at BNB or another bank in Bhutan, and the app handles registration, KYC checks, beneficiaries and exchange rates.

This post is what I learned doing that work. It's not a cryptography lecture. It's the practical side: what signing and encryption each protect you from, how they fit together, and the mistakes that are easy to make in C#.

Signing and encryption solve different problems

The first thing to get clear is that signing and encrypting are not the same thing, and you usually need both.

  • Encryption protects confidentiality. Only the intended receiver can read the message.
  • A digital signature protects integrity and authenticity. The receiver can check that the message wasn't changed, and that it really came from the sender who holds the private key.

An encrypted message that isn't signed can still be tampered with in some setups, or sent by someone pretending to be a partner. A signed message that isn't encrypted can be verified by anyone, but it can also be read by anyone. For a payment instruction, with names, account details and amounts, neither of those is acceptable on its own.

There's a third thing people forget: non-repudiation. Because only the sender holds their private key, a valid signature is evidence that they sent the message. When two organisations are moving money, that matters as much as the encryption does.

Symmetric vs asymmetric: why you end up using both

Symmetric encryption (like AES) uses one shared key to encrypt and decrypt. It's fast, and it handles large payloads easily. The hard part is getting that shared key to the other side safely.

Asymmetric cryptography (like RSA) uses a key pair: a public key you can share with anyone, and a private key you never share. It solves the key-sharing problem, but it's much slower and can only encrypt small amounts of data directly.

So in practice, most secure messaging uses a hybrid approach:

  1. Generate a fresh random AES key for each message.
  2. Encrypt the payload with that AES key.
  3. Encrypt the AES key itself with the receiver's RSA public key.
  4. Sign the result with the sender's RSA private key.

The receiver does the reverse: verify the signature first, then decrypt the AES key with their private key, then decrypt the payload.

On the remit projects, we used symmetric and asymmetric encryption together with digital signatures to secure transactions.

Example: signing a payload in C#

Here's a generic example of signing and verifying a JSON payload with RSA in .NET. This is illustrative code for this post, not the production code from the projects.

using System.Security.Cryptography;
using System.Text;

public static class PayloadSigner
{
    // Example only: sign the exact bytes you will send.
    public static string Sign(string payloadJson, RSA privateKey)
    {
        byte[] data = Encoding.UTF8.GetBytes(payloadJson);
        byte[] signature = privateKey.SignData(
            data,
            HashAlgorithmName.SHA256,
            RSASignaturePadding.Pss);

        return Convert.ToBase64String(signature);
    }

    public static bool Verify(string payloadJson, string signatureBase64, RSA publicKey)
    {
        byte[] data = Encoding.UTF8.GetBytes(payloadJson);
        byte[] signature = Convert.FromBase64String(signatureBase64);

        return publicKey.VerifyData(
            data,
            signature,
            HashAlgorithmName.SHA256,
            RSASignaturePadding.Pss);
    }
}

A few things worth noticing:

  • Sign bytes, not objects. If you serialise the object, sign it, then serialise it again to send, the two strings may not match. Different property order or whitespace and the signature fails. Sign the exact bytes that go on the wire.
  • Pick the padding deliberately. PSS is the modern choice for RSA signatures. If a partner requires PKCS#1 v1.5, that's a contract, not something to guess. Both sides must agree.
  • Verify before you trust anything. Don't parse the payload and start acting on it, then check the signature. Verify first, then process.

Example: encrypting the payload with AES-GCM

For the encryption step, AES-GCM is a good default in modern .NET. It's authenticated encryption, so it detects tampering with the ciphertext as well as hiding it. Again, this is an example, not production code.

using System.Security.Cryptography;

public sealed record EncryptedPayload(byte[] Nonce, byte[] Ciphertext, byte[] Tag, byte[] EncryptedKey);

public static class PayloadEncryptor
{
    // Example only: hybrid encryption with a fresh AES key per message.
    public static EncryptedPayload Encrypt(byte[] plaintext, RSA receiverPublicKey)
    {
        byte[] aesKey = RandomNumberGenerator.GetBytes(32);   // AES-256
        byte[] nonce = RandomNumberGenerator.GetBytes(12);    // never reuse with the same key
        byte[] ciphertext = new byte[plaintext.Length];
        byte[] tag = new byte[16];

        using (var aes = new AesGcm(aesKey, tagSizeInBytes: 16))
        {
            aes.Encrypt(nonce, plaintext, ciphertext, tag);
        }

        byte[] encryptedKey = receiverPublicKey.Encrypt(aesKey, RSAEncryptionPadding.OaepSHA256);
        CryptographicOperations.ZeroMemory(aesKey);

        return new EncryptedPayload(nonce, ciphertext, tag, encryptedKey);
    }

    public static byte[] Decrypt(EncryptedPayload payload, RSA receiverPrivateKey)
    {
        byte[] aesKey = receiverPrivateKey.Decrypt(payload.EncryptedKey, RSAEncryptionPadding.OaepSHA256);
        byte[] plaintext = new byte[payload.Ciphertext.Length];

        try
        {
            using var aes = new AesGcm(aesKey, tagSizeInBytes: 16);
            aes.Decrypt(payload.Nonce, payload.Ciphertext, payload.Tag, plaintext);
            return plaintext;
        }
        finally
        {
            CryptographicOperations.ZeroMemory(aesKey);
        }
    }
}

If anyone changes a single byte of the ciphertext, the nonce or the tag, Decrypt throws a CryptographicException. That's exactly what you want. Treat it as a hard failure, log it, and reject the message.

Lessons I'd pass on

1. Never roll your own crypto

This sounds obvious, but the temptation shows up in small ways: a "simple" XOR, a home-made key derivation, a custom padding scheme. Use the algorithms built into System.Security.Cryptography, use them the way they're documented, and let the people who specialise in cryptography do the maths.

2. Agree on the format with your partner, in writing

Most of the bugs in signed and encrypted integrations aren't cryptography bugs. They're format bugs. Which encoding? Base64 or Base64Url? Which fields are signed? What order? Is the signature in a header or the body? Write it down, share sample payloads with real (test) signatures, and test against them on both sides before anything else.

3. Protect against replay

A valid signed message is still valid if someone captures it and sends it again. For payment instructions that's a serious problem. Include a unique message id and a timestamp inside the signed data, reject anything too old, and keep track of ids you've already processed. Idempotency in the payment logic is the second line of defence.

4. Keys don't belong in code or config files

A perfect encryption scheme is useless if the private key is sitting in appsettings.json in a Git repo. On these projects we used AWS, including Secrets Manager, and that's the kind of place keys and secrets belong. Load them at runtime, restrict who and what can read them, and plan for rotation from day one, not after a scare.

5. Log the event, never the secret

When a signature fails or a decryption throws, you need to know about it. But be careful what goes into the logs. Log the message id, the partner, the time and the type of failure. Never log the plaintext payload, the decrypted key, or the private key. In payments, logs end up in a lot more places than you think.

6. Make failure loud and safe

If verification fails, the answer is "no". Not "log a warning and continue". Not "try a different key until one works". Reject the message, return a clear error to the sender, and alert someone. Silent fallbacks in security code are where incidents start.

Looking back

The biggest lesson wasn't any single algorithm. It was that security in a payment system is mostly about discipline: clear contracts with partners, keys kept somewhere safe, and code that refuses to carry on when something doesn't check out. The cryptography libraries in .NET are excellent. The hard part is everything around them.

Final thoughts

If you're building anything that moves money or sensitive data between organisations, get comfortable with the difference between signing and encrypting, use hybrid encryption with the tools .NET already gives you, and spend more time on key management and message formats than you think you need to.

I'll write more about the remittance work in future posts, including when I chose symmetric versus asymmetric encryption, and how we kept secrets out of the code with AWS Secrets Manager.

Have you worked on signed or encrypted integrations with a bank or payment partner? What tripped you up? Tell me in the comments.

X / Twitter LinkedIn

Comments (0)

No comments yet. Be the first!

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me