Message Body Encryption

Component: NServiceBus
NuGet Package NServiceBus (5.x)

Introduction

This sample shows how to use IMutateTransportMessages to encrypt/decrypt the binary data of a message as it passes through the pipeline.

Run the solution.

Set both Endpoint1 and Endpoint2 as startup projects and run the solution. Endpoint1 encrypts a message and sends it while Endpoint2 receives the encrypted message and decrypts it.

Code walk-through

The message contract

Starting with the Shared project, open CompleteOrder.cs:

public class CompleteOrder :
    IMessage
{
    public string CreditCard { get; set; }
}

Note that it does not need any custom property types to be encrypted.

How is encryption configured.

Open either one of the Program.cs files. Notice the line:

busConfiguration.RegisterMessageEncryptor();

This is an extension method that adds an IMutateTransportMessages to the configuration.

public static class BusConfigExtensions
{
    public static void RegisterMessageEncryptor(this BusConfiguration busConfiguration)
    {
        busConfiguration.RegisterComponents(
            registration: components =>
            {
                components.ConfigureComponent<MessageEncryptor>(DependencyLifecycle.InstancePerCall);
            });
    }
}

The Mutator

This is for demonstration purposes and is not true encryption. It is only doing a byte array reversal to illustrate the API. In a production system, encryption should be used via the .NET Framework Cryptography Model or some other secure mechanism.
public class MessageEncryptor :
    IMutateTransportMessages
{
    public void MutateIncoming(TransportMessage transportMessage)
    {
        transportMessage.Body = transportMessage.Body.Reverse().ToArray();
    }

    public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
    {
        transportMessage.Body = transportMessage.Body.Reverse().ToArray();
    }
}

Related Articles


Last modified