检查EXE上的数字签名

我的.NET exe是使用signtool签名的。 使用此代码,我可以validation证书本身的有效性:

var cert = X509Certificate.CreateFromSignedFile("application.exe"); var cert2 = new X509Certificate2(cert.Handle); bool valid = cert2.Verify(); 

但是,这仅检查证书本身,而不检查EXE的签名。 因此,如果EXE被篡改,则此方法不会检测到它。

我该如何查看签名?

您需要从wintrust.dll调用(P / Invoke) WinVerifyTrust()函数。 (据我所知)在托管.NET中没有其他选择。

您可以在此处找到此方法的文档。

有人已经问过这个问题了。 它不被接受,但它应该是正确的(我只滚动)。 看一看。

您也可以查看本指南,但他们也是如此。

要validation签名.exe文件的完整性,我们可以使用StrongNameSignatureVerificationEx方法:

 [DllImport("mscoree.dll", CharSet = CharSet.Unicode)] public static extern bool StrongNameSignatureVerificationEx( string wszFilePath, bool fForceVerification, ref bool pfWasVerified); var assembly = Assembly.GetExecutingAssembly(); bool pfWasVerified = false; if (!StrongNameSignatureVerificationEx(assembly.Location, true, ref pfWasVerified)) { // it's a patched .exe file! } 

但这还不够。 可以删除签名,然后再次应用/重新创建它! (有很多工具可以做到这一点)在这种情况下,您需要将签名的公钥存储在某处(作为资源),然后将其与新/当前公钥进行比较。 更多信息在这里

我搜索了github并找到了使用PowerShell对象检查有效Authenticode签名的Azure Microsoft C# 代码 。

  ///  /// Check for Authenticode Signature ///  ///  ///  private bool VerifyAuthenticodeSignature(string providedFilePath) { bool isSigned = true; string fileName = Path.GetFileName(providedFilePath); string calculatedFullPath = Path.GetFullPath(providedFilePath); if (File.Exists(calculatedFullPath)) { Log.LogMessage(string.Format("Verifying file '{0}'", calculatedFullPath)); using (PowerShell ps = PowerShell.Create()) { ps.AddCommand("Get-AuthenticodeSignature", true); ps.AddParameter("FilePath", calculatedFullPath); var cmdLetResults = ps.Invoke(); foreach (PSObject result in cmdLetResults) { Signature s = (Signature)result.BaseObject; isSigned = s.Status.Equals(SignatureStatus.Valid); if (isSigned == false) { ErrorList.Add(string.Format("!!!AuthenticodeSignature status is '{0}' for file '{1}' !!!", s.Status.ToString(), calculatedFullPath)); } else { Log.LogMessage(string.Format("!!!AuthenticodeSignature status is '{0}' for file '{1}' !!!", s.Status.ToString(), calculatedFullPath)); } break; } } } else { ErrorList.Add(string.Format("File '{0}' does not exist. Unable to verify AuthenticodeSignature", calculatedFullPath)); isSigned = false; } return isSigned; }