title: CMS signing in .NET with certificate chain not in local trusted certificate store
body: <p>I have X509 certificates that are stored on the network. I can read the chain from remote windows certificate store. I need to sign some data and include chain to the signature to make it possible to validate it later.</p>
  
  <p>The problem is that I can't find a way to put certificate chain to the CsmSigner. I have read that it takes certificate from constructor parameter and tries to build a chain with X509Chain.Build. It ignores Certificates list values and fails (obviously) because no certificate can be found in the local Windows cert store.</p>
  
  <p>Please find below my test code (that works only if certificates were saved locally to the windows cert store)</p>
  
  <pre><code>protected byte[] SignWithSystem(byte[] data, X509Certificate2 cert, X509Certificate[] chain)
  {
      ContentInfo contentInfo = new ContentInfo(data);
  
      SignedCms signedCms = new SignedCms(contentInfo, true);
  
      CmsSigner cmsSigner = new CmsSigner(cert);
      cmsSigner.DigestAlgorithm = new Oid("2.16.840.1.101.3.4.2.1"); //sha256
      cmsSigner.IncludeOption = X509IncludeOption.WholeChain;
  
      if (chain != null)
      {
          //adding cert chain to signer
          cmsSigner.Certificates.AddRange(chain);
          signedCms.Certificates.AddRange(chain);
      }
  
      signedCms.ComputeSignature(cmsSigner); //fails here with System.Security.Cryptography.CryptographicException : A certificate chain could not be built to a trusted root authority.
  
  
      byte[] signedPkcs = signedCms.Encode();
      return signedPkcs;
  }
  </code></pre>
  
  <p>Is there any way to make it work without uploading certificates to the local store? Should I use any alternative signer?</p>
  
  <p>I can try to upload certificates to the store but the problems are that</p>
  
  <ul>
  <li><p>I have to add and remove certificates (permissions have to be granted)</p></li>
  <li><p>There are several processes that applies signature so cross-process synchronization have to be added.</p></li>
  <li><p>This is not that I'd like to do.</p></li>
  </ul>