title: NServiceBus: Message level encryption
body: <p>I have the requirement that the content of all messages must be encrypted in some way. For the actual encryption, I can probably leverage the built in X.509 encryption. </p>
  
  <p>However, I'm wondering what the best way to do message level encryption is, without having to modify the messages themselves (so no <code>WireEncryptedString</code>). I can see that the latest version in development will offer some more support for this in the form of <code>IMutateOutgoingMessages</code>, <code>IMutateIncomingMessages</code> and <code>IMapOutgoingTransportMessages</code>. Especially the last one is interesting as it gets passed a <code>Stream</code> that I'll be able to encrypt in its entirety (right?). I've seen this approach used <a href="http://abstractast.com/2010/09/extending-nservicebus/" rel="nofollow">here</a> and he correctly mentions that there is no <code>IMapIncomingTransportMessages</code>, so how would I go about decrypting the encrypted message on the receiving side without modifying NServiceBus code, or is that currently the only option until that gets fleshed out? </p>
  
  <p>However, that's the future version of NServiceBus and I don't think it's a good idea to use that in a production scenario right now. How would I go about doing this in 2.0? To me, the best way seems to be to write a custom <code>EncryptedSerializer</code> that gets passed in <code>IMessageSerializer</code> and basically just wraps the <code>Serialize</code> and <code>Deserialize</code> methods of that <code>IMessageSerializer</code>. </p>
  
  <p>What I currently have:</p>
  
  <pre><code>public class EncryptedSerializer : IMessageSerializer
  {
    [Inject]
    public MessageSerializer Serializer { get; set; }
  
    public IMessage[] Deserialize(System.IO.Stream stream)
    {
      // decrypt magic happens here
      return Serializer.Deserialize(stream);
    }
  
    public void Serialize(IMessage[] messages, System.IO.Stream stream)
    {
      Serializer.Serialize(messages, stream);
      // encrypt magic happens here
    }
  }
  </code></pre>
  
  <p>But I can't figure out how to setup the NServiceBus configuration that it gets passed in an XmlSerializer that is correctly configured/injected as well. I've looked at the <code>.XmlSerializer()</code> extension method and tried to replicate that, but with no luck. And ideally, I would want to have just a <code>IMessageSerializer</code> instead of the concrete XML serializer, but that's of lesser concern.</p>
  
  <p>I use Ninject and the Ninject object builder for NServiceBus from here: gist.github.com/326321. But I'm not sure if that's important.</p>