Introduction

When encrypting a SOAP message using WSE 2.0, the default behavior is to encrypt the body of the SOAP message only. What if you wish to encrypt more of the message? The listing below shows how I went about encrypting the UsernameToken and Signature elements of a message. It should be noted that the solution developed did not route messages through an intermediary so encrypting the signature was not an issue.

The code

//
// Sign the Message using a UsernameToken
//

// Create the UsernameToken we use to sign the message
UsernameToken userToken = new UsernameToken("phil", "notverysecret",
PasswordOption.SendNone);

// Sign the message with the UsernameToken
MessageSignature sig = new MessageSignature(userToken);
requestContext.Security.Elements.Add(sig);

//
// Encrypt elements in the SOAP header using an X509 cert.
//

//  First of all create an encrypting token
X509SecurityToken encryptingToken = GetServerToken();

// Encrypt the UsernameToken element in the SOAP header
requestContext.Security.Elements.Add(
new EncryptedData( encryptingToken, "#" + userToken.Id ) );

// The Signature element doesn't have an Id - we need to create one
Guid id = Guid.NewGuid();

// Assign the Id we created to the Signature
sig.Signature.Id = id.ToString();

requestContext.Security.Elements.Add(
new EncryptedData( encryptingToken, "#" + sig.Signature.Id) );

Note on WSE 3.0

If you are using WSE 3.0 rather than WSE 2.0 things should be easier. I haven't used WSE 3.0 myself as yet, but I understand encrypting the digital signature is now better supported and more straightforward.