Search code examples
c#wcfwcf-securityx509certificate2

Resolve WCF Error: The EncryptedKey clause was not wrapped with the required encryption token 'System.IdentityModel.Tokens.X509SecurityToken'


I have a WCF client that is crashing with the error "The EncryptedKey clause was not wrapped with the required encryption token 'System.IdentityModel.Tokens.X509SecurityToken'." for every response.

I've looked around and this blog post seems to indicate that the problem is with my certificate set up, but I'm not sure what I am doing wrong...

My client uses a custom binding with a MutualCertificateBindingElement for security, I am configuring the certificates in code as follows:

client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;
client.ClientCredentials.ServiceCertificate.SetDefaultCertificate
(
    StoreLocation.CurrentUser,
    StoreName.AddressBook,
    X509FindType.FindBySerialNumber,
    "[serial number 1]"
);

client.ClientCredentials.ClientCertificate.SetCertificate
(
    StoreLocation.CurrentUser,
    StoreName.My,
    X509FindType.FindBySerialNumber,
    "[serial number 2]"
);

The serial numbers match the values in the <X509SerialNumber> elements in both the request and the response messages.

One discrepancy I have noticed is the <X509IssuerName> elements in the request and the response are formatted differently:

Request:  CN=[CN], O=[O], L=[L], C=[C]
Response: C=[C],L=[L],O=[O],CN=[CN]

Is it possible this is causing the issue?

UPDATE

Turns out it was the certificate name formatting causing the issue. I managed to resolve it by replacing the cert names in the response with what WCF expects by using a custom encoder. Now I have this ugly hack, but it works so I'll live with it!

public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
{   
    var msgContents = new byte[buffer.Count];
    Array.Copy(buffer.Array, buffer.Offset, msgContents, 0, msgContents.Length);
    bufferManager.ReturnBuffer(buffer.Array);
    var message = Encoding.UTF8.GetString(msgContents);

    // Fix certificate issuer name formatting to match what WCF expects.
    message = message.Replace
    (
        "C=[C],L=[L],O=[O],CN=[CN]",
        "CN=[CN], O=[O], L=[L], C=[C]"
    );

    var stream = new MemoryStream(Encoding.UTF8.GetBytes(message));     
    return ReadMessage(stream, int.MaxValue);
}

Solution

  • The issuer name order that you mentioned is most probably the issue. Since these names are not signed I suggest you write a custom encoder in your client that replaces the names in the response to be formatted as in the request.