Message Body Encryption

Component: NServiceBus
NuGet Package NServiceBus (6.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:

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

endpointConfiguration.RegisterMessageEncryptor();

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

public static class EndpointConfigurationExtensions
{
    public static void RegisterMessageEncryptor(this EndpointConfiguration endpointConfiguration)
    {
        endpointConfiguration.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.
public class MessageEncryptor :
    IMutateIncomingTransportMessages,
    IMutateOutgoingTransportMessages
{

    public Task MutateIncoming(MutateIncomingTransportMessageContext context)
    {
        context.Body = context.Body.Reverse().ToArray();
        return Task.CompletedTask;
    }

    public Task MutateOutgoing(MutateOutgoingTransportMessageContext context)
    {
        context.OutgoingBody = context.OutgoingBody.Reverse().ToArray();
        return Task.CompletedTask;
    }
}

Related Articles


Last modified