title: C# Add wsse:Security and BinarySecurityToken to Envelope xml file programmatically without Web Reference
body: <p>Currently I have to generate an XML file, simulating a SOAP request, this file should be signed with an X.509 certificate</p>
  
  <p>At this moment I have this method to sign the file</p>
  
  <pre><code>public static void SignXml(XmlDocument xmlDoc, X509Certificate2 uidCert)
  {
      CspParameters cspParams = new CspParameters();
      cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
  
      RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
  
      // Check arguments. 
      if (xmlDoc == null)
          throw new ArgumentException("xmlDoc");
      if (rsaKey == null)
          throw new ArgumentException("Key");
  
      // Create a SignedXml object.
      SignedXml signedXml = new SignedXml(xmlDoc);
  
      // Add the key to the SignedXml document.
      signedXml.SigningKey = rsaKey;
  
      // Specify a canonicalization method.
      signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
  
      // Set the InclusiveNamespacesPrefixList property.        
      XmlDsigExcC14NTransform canMethod = (XmlDsigExcC14NTransform)signedXml.SignedInfo.CanonicalizationMethodObject;
      canMethod.InclusiveNamespacesPrefixList = "sol soapenv";
  
      // Create a reference to be signed.
      Reference reference = new Reference();
      Reference reference1 = new Reference();
      reference.Uri = "";            
      reference1.Uri = "";
  
      string referenceDigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
      reference.DigestMethod = referenceDigestMethod;
      reference1.DigestMethod = referenceDigestMethod;
  
      // Add an enveloped transformation to the reference.
      //XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
      //reference.AddTransform(env);
  
      XmlDsigExcC14NTransform c14n = new XmlDsigExcC14NTransform();
      c14n.InclusiveNamespacesPrefixList = "wsse sol soapenv";
  
      reference.AddTransform(c14n);
  
      XmlDsigExcC14NTransform c14n1 = new XmlDsigExcC14NTransform();
      c14n1.InclusiveNamespacesPrefixList = "sol";
      reference1.AddTransform(c14n1);
  
      // Add the reference to the SignedXml object.
      signedXml.AddReference(reference);
      signedXml.AddReference(reference1);
  
      // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
      KeyInfo keyInfo = new KeyInfo();
  
      SecurityTokenReference skr = new SecurityTokenReference();
      skr.Reference = "some";
      skr.ValueType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
  
      keyInfo.AddClause(skr);
      signedXml.KeyInfo = keyInfo;
  
      // Compute the signature.
      signedXml.ComputeSignature();
  
      // Get the XML representation of the signature and save 
      // it to an XmlElement object.
      XmlElement xmlDigitalSignature = signedXml.GetXml();
  
      System.Console.WriteLine(signedXml.GetXml().InnerXml);
  
      // Append the element to the XML docu0ment.
      //xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
      XmlElement root = (XmlElement)xmlDoc.GetElementsByTagName("soapenv:Envelope")[0];
      string query = string.Format("//*[@Id='{0}']", "IDH"); //Search the Header tag to add signature
      XmlElement myElement = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode(query);
      myElement.AppendChild(xmlDigitalSignature);
  }
  </code></pre>
  
  <p>I can generate this file</p>
  
  <pre><code>&lt;soapenv:Envelope xmlns:sol="
  http://www.sol.com" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"&gt;
      &lt;soapenv:Header Id="IDH"&gt;
          &lt;sol:authentication&gt;
              &lt;id&gt;4942014103&lt;/id&gt;
              &lt;userid&gt;ME.8494&lt;/userid&gt;
          &lt;/sol:authentication&gt;
          &lt;Signature xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;
              &lt;SignedInfo&gt;
                  &lt;CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"&gt;
                      &lt;InclusiveNamespaces PrefixList="sol soapenv" xmlns="http://www.w3.org/2001/10/xml-exc-c14n#"/&gt;
                  &lt;/CanonicalizationMethod&gt;
                  &lt;SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/&gt;
                  &lt;Reference URI=""&gt;
                      &lt;Transforms&gt;
                          &lt;Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"&gt;
                              &lt;InclusiveNamespaces PrefixList="wsse sol soapenv" xmlns="http://www.w3.org/2001/10/xml-exc-c14n#"/&gt;
                          &lt;/Transform&gt;
                      &lt;/Transforms&gt;
                      &lt;DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/&gt;
                      &lt;DigestValue&gt;BEZBfqQ1QGgbhxvtB83/tr2Yt/8uJPEfvrh8Tn5O6oQ=&lt;/DigestValue&gt;
                  &lt;/Reference&gt;
                  &lt;Reference URI=""&gt;
                      &lt;Transforms&gt;
                          &lt;Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"&gt;
                              &lt;InclusiveNamespaces PrefixList="sol" xmlns="http://www.w3.org/2001/10/xml-exc-c14n#"/&gt;
                          &lt;/Transform&gt;
                      &lt;/Transforms&gt;
                      &lt;DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/&gt;
                      &lt;DigestValue&gt;BEZBfqQ1QGgbhxvtB83/tr2Yt/8uJPEfvrh8Tn5O6oQ=&lt;/DigestValue&gt;
                  &lt;/Reference&gt;
              &lt;/SignedInfo&gt;
              &lt;SignatureValue&gt;MiOL7D2YfIModsGXh+mm+Ok+oApaYMNenX8xFgwMCXcxW7blHqAPJ2VKGhraAdqy9crAvzEgT6MqD/T9ZWPnK1IHOcQlCt5XICkAlJVnLB78rWkYaTsjNLak2KSvQVCqEDIp0GEwGE6S+5cJykWmbOGiZg50VFFN8QRUlYiIB8I=&lt;/SignatureValue&gt;
              &lt;KeyInfo&gt;
                  &lt;wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"&gt;
                      &lt;wsse:Reference URI="#some" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/&gt;
                  &lt;/wsse:SecurityTokenReference&gt;
              &lt;/KeyInfo&gt;
          &lt;/Signature&gt;
      &lt;/soapenv:Header&gt;
      &lt;soapenv:Body&gt;
          &lt;sol:solbus&gt;
              &lt;in&gt;H4sIAAAAAAAEAI1VXW+bMBR9n7T/YPFcvgJJW9RQUZJ0aAnpAp26vVQWOK2lgCPjJM2/nwEHTEKk8cY59/heHx/Dw+NXtgF7RAtM8rFiaoby6H7/9rBmiTPzYt97X079CeBFeeFWF8FXisfDK2dXT9cDhoB0sj9EMfGIapvy3mUfKJMqjivGAwT5AiVMUajpUdzR2CktRhGHGIrdeQJZAdt/xtbyryBOZJyGc4F1aqUsBnBKCacoGKAn6gaIuSCuQw7+hEKE9x/uGTbAvzYxC684n39+VZuy8fLZpr9p39oPdWSqvEFOZFhhmrCnY5o0d38Vbr+jhJukIJwnuJe41q3QUhicRmYu6LW9lfS2S4FDeaGm/nuWxdY5fOdQ19pmS37e7AS5LSqrrkfCRB/iCbFFGJFHS5jT1Od3DT4ZqwFfIptGku+g+njRq/UoY9Uu9HqjUc3Yk4NfesUxvCDL1/GYblvf/aoYKc1YiqGaYFK0vdhbcKPDCZzsFq6QfLeu2W7lXPoWDjZeR7oRA16NlU+n+MdSXNEtnn3HXbepJtgRdv9RN4v6fh6xR4/CVeTMMYmDdg4oVPr6sN34MjNGSdaVxPvryl/nHFITD+KYYbzNqPloz1SJ4wZZ9BviZA7+ZKvxqsmroWSTmvT3BT/k9AsqO0dGusLN5CRerUWaoT/bN71F6Ymjh9q6S36nngMxEmBLFwcAAA==&lt;/in&gt;
          &lt;/sol:solbus&gt;
      &lt;/soapenv:Body&gt;
  &lt;/soapenv:Envelope&gt;
  </code></pre>
  
  <p>In method SingXml xmlDoc contains this xml, anfter sing I add to header</p>
  
  <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sol="http://www.sol.com"&gt;
    &lt;soapenv:Header Id="IDH"&gt;
      &lt;sol:authentication&gt;
        &lt;id&gt;&lt;/id&gt;&lt;userid&gt;&lt;/userid&gt; &lt;------ With info
      &lt;/sol:authentication&gt;
    &lt;/soapenv:Header&gt;
    &lt;soapenv:Body&gt;
      &lt;sol:siatbus&gt;
        &lt;in&gt;&lt;/in&gt; &lt;-----With info
      &lt;/sol:siatbus&gt;
    &lt;/soapenv:Body&gt;
  &lt;/soapenv:Envelope&gt;
  </code></pre>
  
  <p><strong>I need something more, Signature must be within a Security tag inside Header tag, with a  BinarySecurityToken element</strong></p>
  
  <p>For example</p>
  
  <pre><code>&lt;soapenv:Header&gt; &lt;!-- extrac of the example file --&gt;
    &lt;wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu=" http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"&gt;
      &lt;wsse:BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="X509-D53CCD6983E4CE0BD7142791021078262"&gt;
          MIIDbDgg4iF74cqiF6NcnzBnD9qA2MB6hSo38e0RISilEFSzWikDqBtOjgm7ux9fdeHojDm4uvhsSfbEyGmGTAQRzg9yIiD3ovjOzuZsf+I3HWS9F6xl6sb2+wvYXD4DFk/OD+N7UszGsoWFZg
      &lt;/wsse:BinarySecurityToken&gt;
      &lt;ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"&gt;
            .....
      &lt;/ds:Signature&gt;
  </code></pre>
  
  <p>I can add <code>&lt;wsse:Security</code> tag with hard code String, but 
  I do not know if it affects the BinarySecurityToken inside</p>
  
  <p>How is the internal data (<code>MIIDbDgg4i</code>....) of the token is generated?</p>
  
  <p><strong>What I have to do to add the <code>Security</code> tag?</strong></p>
  
  <p>Extra</p>
  
  <p>How I can add the prefix <code>ds</code> to the Signature and its children?</p>