Message Body Encryption

Component: NServiceBus
NuGet Package NServiceBus (6.x)


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


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

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

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 :

    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