title: WS-Federation - decrypt Cookie from SecurityContextToken
body: <p>We have implemented WSFederation and we would like to have integration tests, for that we would need to be able to get User Claims from idsrvauth Cookie. </p>
  
  <p>I'm able to get idsrvauth and idsrvauth1 cookie. And then with following code I try to decode cookie</p>
  
  <pre class="lang-cs prettyprint-override"><code>var auth = WebResp.Cookies["idsrvauth"].Value + WebResp.Cookies["idsrvauth1"].Value;
  
  byte[] authBytes = Convert.FromBase64String(auth);
  string decodedString = Encoding.UTF8.GetString(authBytes);         
  
  
  var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
  store.Open(OpenFlags.ReadOnly);
  var thumbprint = "********";
  var certs = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
  
  List&lt;CookieTransform&gt; sessionTransforms = new List&lt;CookieTransform&gt;(new CookieTransform[]
     {
          new DeflateCookieTransform(),
          new RsaSignatureCookieTransform(certs[0]),
          new RsaEncryptionCookieTransform(certs[0])
     });
  
  SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
  
  SecurityTokenResolver resolver;
  {
      var token = new X509SecurityToken(certs[0]);    
      var tokens = new List&lt;SecurityToken&gt;() { token };    
      resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false);
  }
  
  sessionHandler.Configuration = new SecurityTokenHandlerConfiguration();
  sessionHandler.Configuration.IssuerTokenResolver = resolver;
  
  
  var xmlSett = new XmlReaderSettings();
  
  using (var reader = XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes(decodedString)), xmlSett))
  {
      var theToken = sessionHandler.ReadToken(reader);
  }
  </code></pre>
  
  <p>Decoded and combined cookies (idsrvauth and idsrvauth1) look like:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;SecurityContextToken p1:Id="_564051b3-57ad-41de-831f-41beda49d8e8-7D534CD4043540BBB2EE96A4ADB59C42" xmlns:p1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns="http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512"&gt;
    &lt;Identifier&gt;urn:uuid:8614f321-2f9d-4332-a1d9-8ea00190bd52
    &lt;/Identifier&gt;
    &lt;Cookie xmlns="http://schemas.microsoft.com/ws/2006/05/security"&gt;AAEAAA *** [Totaly 2064 chars]
    &lt;/Cookie&gt;
  &lt;/SecurityContextToken&gt;
  </code></pre>
  
  <p>All I get while trying to get token (sessionHandler.ReadToken(reader)) is error :</p>
  
  <p><strong>Additional information: ID1006: The format of the data is incorrect. The encryption key length is negative: '-666895530'. The cookie may have been truncated.</strong></p>
  
  <p>Is the approach correct ? Any help would be appreciated :-)</p>