Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Message body encryption

Component: NServiceBus
NuGet Package: NServiceBus (9.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 :
    IMessage
{
    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:

endpointConfiguration.RegisterMessageEncryptor();

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:

public class MessageEncryptor :
    IMutateIncomingTransportMessages,
    IMutateOutgoingTransportMessages
{

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

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

Related Articles