Message Body Encryption

Component: NServiceBus | Nuget: NServiceBus (Version: 5.x)

Introduction

This Sample shows how to use IMutateTransportMessages to (fake) encrypt/decrypt the binary data of a message as it passed through the pipeline.

Run the solution.

Set both Endpoint1 and Endpoint2 as projects and run the solution.

Endpoint1

Which encrypts and sends the message.

Endpoint2

Which receives and decrypts the message.

Code walk-through

The message contract

Starting with the Shared project, open the CompleteOrder.cs file and look at the following code:

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

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

How is encryption configured.

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

Edit
busConfiguration.RegisterMessageEncryptor();

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

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

The Mutator

Clearly this it not true encryption. It is only doing a byte array reversal to illustrate the API. In the production system true encryption should be used via the .NET Framework Cryptography Model.
Edit
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