Message body encryption

Component: NServiceBus
NuGet Package: NServiceBus (7.x)

This sample demonstrates how to use IMutateTransportMessages to encrypt and decrypt the binary representation of a message as it passes through the pipeline.

Running the solution starts two console applications. Endpoint1 encrypts a message and sends it and Endpoint2 receives the encrypted message and decrypts it.

Endpoint1 output

Message sent.

Endpoint2 output

CompleteOrderHandler Received CompleteOrder with credit card number 123-456-789

Code walk-through

Message contract

The Shared project contains CompleteOrder.cs, which defines the message contract:

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

Note that a custom property type is not required.

Encryption configuration

Encryption is enabled by calling an extension method in Program.cs in both Endpoint1 and Endpoint2:


The extension method is in Shared/EncryptionExtensions.cs:

public static class EndpointConfigurationExtensions
    public static void RegisterMessageEncryptor(this EndpointConfiguration endpointConfiguration)
        endpointConfiguration.RegisterMessageMutator(new MessageEncryptor());

The mutator is in Shared/MessageEncryptor.cs:

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 performed used 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