Message Body Encryption

Component: NServiceBus
NuGet Package NServiceBus (6.x)


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.


Which encrypts and sends the message.


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 :
    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


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

public static class EndpointConfigurationExtensions
    public static void RegisterMessageEncryptor(this EndpointConfiguration endpointConfiguration)
            registration: components =>

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 :

    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