public void Serialize <T>(Stream output, ISendContext <T> context) where T : class { try { using (var clearStream = new MemoryStream()) { _wrappedSerializer.Serialize(clearStream, context); using (var readStream = new MemoryStream(clearStream.ToArray(), false)) { using (ICryptographyService cryptographyService = new RijndaelCryptographyService(_key)) { EncryptedStream encryptedStream = cryptographyService.Encrypt(readStream); var encryptedMessage = new EncryptedMessageEnvelope { CipheredMessage = Convert.ToBase64String(encryptedStream.GetBytes()), Iv = Convert.ToBase64String(encryptedStream.Iv), }; // Encrypt message and set context var encryptedContext = new SendContext <EncryptedMessageEnvelope>(encryptedMessage); encryptedContext.SetUsing(context); encryptedContext.SetMessageType(typeof(EncryptedMessageEnvelope)); // Serialize secure message to output _wrappedSerializer.Serialize(output, encryptedContext); // Set the encrypted context back into the send context encryptedContext.SetContentType(ContentTypeHeaderValue); context.SetUsing(encryptedContext); } } } } catch (SerializationException) { throw; } catch (Exception ex) { throw new SerializationException("Failed to serialize message", ex); } }