title: Auto Update Downloading Latest .exe file - how to verify it's not been tampered with?
body: <p>We have a small console application (under 200kb) that will be distributed to clients and we want to ensure they run the latest version (verified by a WCF service). Currently it downloads the new .exe file over HTTPS and replaces the current .exe file with it.</p>
  
  <p>Assuming our server isn't compromised, this would be ok. However we also sign our .exe file with a Code Signing certificate. Is there a way to verify this and delete the file if it doesn't match? We would need to be able to verify and delete the file without it ever being executed in case it is a virus.</p>
  
  <p>How can we verify our signed .exe file? For example, Windows will show if it is invalid:
  <img src="https://i.stack.imgur.com/BdBpF.gif" alt="Failed Digital Signature"></p>
  
  <p>Edit: would this code do the job?</p>
  
  <pre><code>X509Certificate basicSigner = X509Certificate.CreateFromSignedFile(file);
  X509Certificate2 cert = new X509Certificate2(basicSigner);
  if (cert.Subject.Contains("CN=MY COMPANY NAME IN CERTIFICATE"))
      valid = true;
  </code></pre>
  
  <p>Edit: if we also check <code>StrongNameSignatureVerificationEx</code>, it comes back failed if one bit is changed in the file. Perhaps this is enough?</p>
  
  <pre><code>[DllImport("mscoree.dll", CharSet = CharSet.Unicode)]
          static extern bool StrongNameSignatureVerificationEx(string wszFilePath, bool fForceVerification, ref bool pfWasVerified); 
  </code></pre>
  
  <p>Edit: I've implemented this code too which calls <strong>WinVerifyTrust</strong> in <strong>WinTrust.dll</strong> to actually verify the Authenticode signature: <a href="http://www.pinvoke.net/default.aspx/wintrust.winverifytrust" rel="nofollow noreferrer">http://www.pinvoke.net/default.aspx/wintrust.winverifytrust</a></p>
  
  <p>Now, it checks if the digital signature contains the correct subject, is from a valid trusted root, the signature is valid and if the code is strong named with it's digital signature. This must be safe enough now?</p>