public override bool Execute()
        {
            using (Package package = Package.Open(PackageFile, FileMode.Open))
            {
                try
                {
                    PackageDigitalSignatureManager signatureManager = new PackageDigitalSignatureManager(package);
                    signatureManager.CertificateOption = CertificateEmbeddingOption.InSignaturePart;

                    List<Uri> toSign = package.GetParts().Select(part => part.Uri).ToList();

                    toSign.Add(PackUriHelper.GetRelationshipPartUri(signatureManager.SignatureOrigin));
                    toSign.Add(signatureManager.SignatureOrigin);
                    toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

                    signatureManager.Sign(toSign, new X509Certificate2(Certificate, CertificatePassword));
                    return true;
                }
                catch (Exception ex)
                {
                    Log.LogError("Error signing package: ", ex);
                    return false;
                }
            }
        }
 public static OpenXmlPowerToolsDocument Insert(OpenXmlPowerToolsDocument doc, IEnumerable<string> certificateList)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (Package package = streamDoc.GetPackage())
         {
             foreach (string digitalCertificate in certificateList)
             {
                 X509Certificate x509Certificate = X509Certificate2.CreateFromCertFile(digitalCertificate);
                 PackageDigitalSignatureManager digitalSigntaureManager = new PackageDigitalSignatureManager(package);
                 digitalSigntaureManager.CertificateOption = CertificateEmbeddingOption.InSignaturePart;
                 System.Collections.Generic.List<Uri> partsToSign = new System.Collections.Generic.List<Uri>();
                 //Adds each part to the list, except relationships parts.
                 foreach (PackagePart openPackagePart in package.GetParts())
                 {
                     if (!PackUriHelper.IsRelationshipPartUri(openPackagePart.Uri))
                         partsToSign.Add(openPackagePart.Uri);
                 }
                 List<PackageRelationshipSelector> relationshipSelectors = new List<PackageRelationshipSelector>();
                 //Creates one selector for each package-level relationship, based on id
                 foreach (PackageRelationship relationship in package.GetRelationships())
                 {
                     PackageRelationshipSelector relationshipSelector =
                         new PackageRelationshipSelector(relationship.SourceUri, PackageRelationshipSelectorType.Id, relationship.Id);
                     relationshipSelectors.Add(relationshipSelector);
                 }
                 digitalSigntaureManager.Sign(partsToSign, x509Certificate, relationshipSelectors);
             }
         }
         return streamDoc.GetModifiedDocument();
     }
 }
        private static bool SignVsix(string vsixPackagePath, X509Certificate2 certificate)
        {
            // many thanks to Jeff Wilcox for the idea and code
            // check for details: http://www.jeff.wilcox.name/2010/03/vsixcodesigning/
            using (var package = Package.Open(vsixPackagePath))
            {
                var signatureManager = new PackageDigitalSignatureManager(package);
                signatureManager.CertificateOption = CertificateEmbeddingOption.InSignaturePart;

                var partsToSign = new List<Uri>();
                foreach (var packagePart in package.GetParts())
                {
                    partsToSign.Add(packagePart.Uri);
                }

                partsToSign.Add(PackUriHelper.GetRelationshipPartUri(signatureManager.SignatureOrigin));
                partsToSign.Add(signatureManager.SignatureOrigin);
                partsToSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

                try
                {
                    signatureManager.Sign(partsToSign, certificate);
                }
                catch (CryptographicException)
                {
                    return false;
                }

                return true;
            }
        }
Esempio n. 4
0
        private static void SignAllParts(Package package)
        {
            if (package == null)
                throw new ArgumentNullException("SignAllParts(package)");

            // Create the DigitalSignature Manager
            PackageDigitalSignatureManager dsm =
                new PackageDigitalSignatureManager(package);
            dsm.CertificateOption =
                CertificateEmbeddingOption.InSignaturePart;

            // Create a list of all the part URIs in the package to sign
            // (GetParts() also includes PackageRelationship parts).
            System.Collections.Generic.List<Uri> toSign =
                new System.Collections.Generic.List<Uri>();
            foreach (PackagePart packagePart in package.GetParts())
            {
                // Add all package parts to the list for signing.
                toSign.Add(packagePart.Uri);
            }

            // Add the URI for SignatureOrigin PackageRelationship part.
            // The SignatureOrigin relationship is created when Sign() is called.
            // Signing the SignatureOrigin relationship disables counter-signatures.
            toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin));

            // Also sign the SignatureOrigin part.
            toSign.Add(dsm.SignatureOrigin);

            // Add the package relationship to the signature origin to be signed.
            toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

            // Sign() will prompt the user to select a Certificate to sign with.
            try
            {
                dsm.Sign(toSign);
            }

            // If there are no certificates or the SmartCard manager is
            // not running, catch the exception and show an error message.
            catch (CryptographicException ex)
            {
                MessageBox.Show(
                    "Cannot Sign\n" + ex.Message,
                    "No Digital Certificates Available",
                    MessageBoxButton.OK,
                    MessageBoxImage.Exclamation);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <param name="overrideCurrentSignature"></param>
        /// <from>http://msdn.microsoft.com/en-us/library/system.io.packaging.packagedigitalsignaturemanager.sign(v=vs.100).aspx</from>
        public void Sign(string path, bool overrideCurrentSignature)
        {
            {
                _log.Debug("We're going to try signing {0}, override current signature {1}".format(path,
                                                                                                   overrideCurrentSignature));
                var package = Package.Open(path);

                _log.Debug("Opened {0}".format(path));
                var signatureManager = new PackageDigitalSignatureManager(package)
                    {
                        CertificateOption = CertificateEmbeddingOption.InSignaturePart
                    };

                if (signatureManager.IsSigned)
                {
                    if (overrideCurrentSignature)
                    {
                        _log.Debug("{0} is signed we'll try to remove signatures".format(path));
                        //TODO: make smarter so we only remove signatures for the relevant parts
                        signatureManager.RemoveAllSignatures();
                        package.Flush();
                    }
                    else
                    {
                        _log.Debug("{0} is signed, we're going to throw".format(path));
                        throw new AlreadySignedException();
                    }
                }

                var toSign = package.GetParts().Select(packagePart => packagePart.Uri).ToList();

                toSign.Add(PackUriHelper.GetRelationshipPartUri(signatureManager.SignatureOrigin));
                toSign.Add(signatureManager.SignatureOrigin);
                toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

                _log.Debug("About to start signing {0}".format(path));
                signatureManager.Sign(toSign, Certificate);
                _log.Debug("signed {0}, going to close".format(path));
                package.Close();

                _log.Debug("closed {0}".format(path));
            }
            GC.Collect();
        }
Esempio n. 6
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <from>http://msdn.microsoft.com/en-us/library/system.io.packaging.packagedigitalsignaturemanager.sign(v=vs.100).aspx</from>
        public void Sign(string path)
        {
            var package = Package.Open(path);

            var signatureManager = new PackageDigitalSignatureManager(package);
            signatureManager.CertificateOption = CertificateEmbeddingOption.InSignaturePart;

            var toSign = new List<Uri>();
            foreach (PackagePart packagePart in package.GetParts())
            {
                toSign.Add(packagePart.Uri);
            }

            toSign.Add(PackUriHelper.GetRelationshipPartUri(signatureManager.SignatureOrigin));
            toSign.Add(signatureManager.SignatureOrigin);
            toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

                signatureManager.Sign(toSign, Certificate);
                package.Close();
        }
Esempio n. 7
0
        /// <summary>
        /// Main signing process
        /// </summary>
        /// <param name="package"></param>
        /// <returns></returns>
        private bool SignAllParts(Package package)
        {
            if (package == null)
                throw new ArgumentNullException("SignAllParts(package)");

            // Create the DigitalSignature Manager
            PackageDigitalSignatureManager dsm =
                new PackageDigitalSignatureManager(package);
            dsm.CertificateOption =
                CertificateEmbeddingOption.InSignaturePart;

            // Create a list of all the part URIs in the package to sign
            // (GetParts() also includes PackageRelationship parts).
            System.Collections.Generic.List<Uri> toSign =
                new System.Collections.Generic.List<Uri>();
            foreach (PackagePart packagePart in package.GetParts())
            {
                // Add all package parts to the list for signing.
                toSign.Add(packagePart.Uri);
            }

            // Add the URI for SignatureOrigin PackageRelationship part.
            // The SignatureOrigin relationship is created when Sign() is called.
            // Signing the SignatureOrigin relationship disables counter-signatures.
            toSign.Add(PackUriHelper.GetRelationshipPartUri(dsm.SignatureOrigin));

            // Also sign the SignatureOrigin part.
            toSign.Add(dsm.SignatureOrigin);

            // Add the package relationship to the signature origin to be signed.
            toSign.Add(PackUriHelper.GetRelationshipPartUri(new Uri("/", UriKind.RelativeOrAbsolute)));

            // Sign() will prompt the user to select a Certificate to sign with.
            try
            {
                var cert = new X509Certificate2(this.CertificatePath, (String.IsNullOrEmpty(this.CertificatePassword) ? null : this.CertificatePassword));
                dsm.Sign(toSign, cert);
            }

            // If there are no certificates or the SmartCard manager is
            // not running, catch the exception and show an error message.
            catch (CryptographicException ex)
            {
                Console.WriteLine(
                    "Cannot Sign: {0}", ex.Message);
            }

            return dsm.IsSigned && dsm.VerifySignatures(true) == VerifyResult.Success;
        }
        private void SignAllParts(Package package, X509Certificate2 certificate)
        {
            var partsToSign = new List<Uri>();
            var relationshipsToSign = new List<PackageRelationshipSelector>();

            foreach (var relationship in package.GetRelationshipsByType(RtOfficeDocument))
            {
                AddSignableItems(relationship, partsToSign, relationshipsToSign);
            }

            var mgr = new PackageDigitalSignatureManager(package)
            {
                CertificateOption = CertificateEmbeddingOption.InSignaturePart
            };

            var officeObject = CreateOfficeObject(SignatureID, ManifestHashAlgorithm);
            var officeObjectReference = new Reference("#" + OfficeObjectID);
            mgr.Sign(partsToSign,
                     certificate,
                     relationshipsToSign,
                     SignatureID,
                     new[] { officeObject },
                     new[] { officeObjectReference });
            package.Close();
        }