private static void SignFileInternal(X509Certificate2 cert, Uri timestampUrl, string path, bool targetFrameworkSupportsSha256, System.Resources.ResourceManager resources) { if (cert == null) { throw new ArgumentNullException(nameof(cert)); } if (String.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } if (!FileSystems.Default.FileExists(path)) { throw new FileNotFoundException(String.Format(CultureInfo.InvariantCulture, resources.GetString("SecurityUtil.SignTargetNotFound"), path), path); } bool useSha256 = UseSha256Algorithm(cert) && targetFrameworkSupportsSha256; if (PathUtil.IsPEFile(path)) { if (IsCertInStore(cert)) { SignPEFile(cert, timestampUrl, path, resources, useSha256); } else { throw new InvalidOperationException(resources.GetString("SignFile.CertNotInStore")); } } else { using (RSA rsa = CngLightup.GetRSAPrivateKey(cert)) { if (rsa == null) { throw new ApplicationException(resources.GetString("SecurityUtil.OnlyRSACertsAreAllowed")); } try { var doc = new XmlDocument { PreserveWhitespace = true }; var xrSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore }; using (XmlReader xr = XmlReader.Create(path, xrSettings)) { doc.Load(xr); } var manifest = new SignedCmiManifest2(doc, useSha256); CmiManifestSigner2 signer; if (useSha256 && rsa is RSACryptoServiceProvider) { RSACryptoServiceProvider csp = SignedCmiManifest2.GetFixedRSACryptoServiceProvider(rsa as RSACryptoServiceProvider, useSha256); signer = new CmiManifestSigner2(csp, cert, useSha256); } else { signer = new CmiManifestSigner2(rsa, cert, useSha256); } if (timestampUrl == null) { manifest.Sign(signer); } else { manifest.Sign(signer, timestampUrl.ToString()); } doc.Save(path); } catch (Exception ex) { int exceptionHR = Marshal.GetHRForException(ex); if (exceptionHR == -2147012889 || exceptionHR == -2147012867) { throw new ApplicationException(resources.GetString("SecurityUtil.TimestampUrlNotFound"), ex); } throw new ApplicationException(ex.Message, ex); } } } }