private void SignOpenOfficeXML(Package package) { try { Licensing.ShowDemoMessage(); DigitalCertificate.LogOnEToken(this.DigitalSignatureCertificate); if (package == null) { throw new ArgumentNullException(); } List <Uri> uris = new List <Uri>(); List <PackageRelationshipSelector> packageRelationshipSelectors = new List <PackageRelationshipSelector>(); foreach (PackageRelationship relationshipsByType in package.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument")) { this.CreateListOfSignableItems(relationshipsByType, uris, packageRelationshipSelectors); } PackageDigitalSignatureManager packageDigitalSignatureManager = new PackageDigitalSignatureManager(package) { CertificateOption = CertificateEmbeddingOption.InSignaturePart }; packageDigitalSignatureManager.Sign(uris, this.DigitalSignatureCertificate, packageRelationshipSelectors); } catch { throw; } }
/// <summary> /// Valida arquivos Office geral /// </summary> /// <param name="filePath">Caminho do arquivo a ser validado</param> /// <param name="format">Formato do documento a ser validado</param> /// <param name="onlyRoot"> /// Determina se irá considerar apenas certificados de Autoridades Certificadoras. /// True: Considera apenas certificados de Autoridades Certificadoras. /// False: Considera todos os certificados instalados na máquina. /// Default: True. /// </param> /// <returns>Lista de assinaturas, válidas ou não</returns> internal static SignatureList validate(string filePath, FileFormat format, bool onlyRoot = true) { try { // list to return SignatureList list = new SignatureList(); // open the file Package package; try { package = Package.Open(filePath, FileMode.Open, FileAccess.Read); } catch (NullReferenceException e) { throw new NullReferenceException(e.Message, e.InnerException); } // get the signatures PackageDigitalSignatureManager _dsm = new PackageDigitalSignatureManager(package); _dsm.CertificateOption = CertificateEmbeddingOption.InSignaturePart; // if no signatures found if (_dsm.Signatures == null || _dsm.Signatures.Count == 0) { throw new NoSignatureFoundException(); } // verify all the signatures foreach (PackageDigitalSignature signature in _dsm.Signatures) { list.Add ( new Signature ( filePath, // file path format, // file format getObjective(signature.Signature.GetXml().OuterXml), // objective getSubject(signature.Signer.Subject), // subject signature.SigningTime, // date time validateCertificate((X509Certificate2)signature.Signer, true), // validate the certificate getCertificates((X509Certificate2)signature.Signer, true) // certificate ) { SX509Certificate = (X509Certificate2)signature.Signer, SFileProperties = getFileProperties(package.PackageProperties) } ); } // close the file package.Close(); return(list); } catch (Exception ex) { throw ex; } }
EnsureSignatures() { // // if _reachSignaturs is not null we have already initialized this // if (null != _reachSignatures) { return; } _reachSignatures = new Collection <XpsDigitalSignature>(); PackageDigitalSignatureManager packageSignatures = new PackageDigitalSignatureManager(CurrentXpsManager.MetroPackage); foreach (PackageDigitalSignature packSignature in packageSignatures.Signatures) { XpsDigitalSignature reachSignature = new XpsDigitalSignature(packSignature, this); // // Only add signatures that meet the policy for // signed Document Sequences // if (reachSignature.SignedDocumentSequence != null) { _reachSignatures.Add(reachSignature); } } }
/// <summary> /// Method that Sign the document, he call the others methods and uses the lists and OfficeObject to Sign /// </summary> /// <param name="certificate">the digital certificate that will sign</param> public void SignDocument(X509Certificate2 certificate) { if (certificate != null) { if (DocumentType.Equals(Types.XpsDocument)) { xpsDocument.SignDigitally( certificate, true, XpsDigSigPartAlteringRestrictions.None); } else { List <Uri> partsToSign = new List <Uri>(); List <PackageRelationshipSelector> relationshipsToSign = new List <PackageRelationshipSelector>(); List <Uri> finishedItems = new List <Uri>(); foreach (PackageRelationship relationship in package.GetRelationshipsByType(RT_OfficeDocument)) { AddSignableItems(relationship, partsToSign, relationshipsToSign); } PackageDigitalSignatureManager mgr = new PackageDigitalSignatureManager(package); mgr.CertificateOption = CertificateEmbeddingOption.InSignaturePart; string signatureID = SignatureID; string manifestHashAlgorithm = ManifestHashAlgorithm; System.Security.Cryptography.Xml.DataObject officeObject = CreateOfficeObject(signatureID, manifestHashAlgorithm); Reference officeObjectReference = new Reference("#" + OfficeObjectID); mgr.Sign(partsToSign, certificate, relationshipsToSign, signatureID, new System.Security.Cryptography.Xml.DataObject[] { officeObject }, new Reference[] { officeObjectReference }); } } }
public static PackageDigitalSignature Sign( OpenXmlPackage openXmlPackage, X509Certificate2 certificate, string signatureId = "idPackageSignature") { if (openXmlPackage == null) { throw new ArgumentNullException(nameof(openXmlPackage)); } if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } if (signatureId == null) { throw new ArgumentNullException(nameof(signatureId)); } Package package = openXmlPackage.Package; var dsm = new PackageDigitalSignatureManager(package) { CertificateOption = CertificateEmbeddingOption.InSignaturePart }; return(dsm.Sign(GetParts(package), certificate, GetRelationshipSelectors(package), signatureId)); }
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); } } }
private static bool ValidatePackageCertificates(PackageDigitalSignatureManager dsm) { Dictionary <string, X509Certificate> certs = GetPackageCertificates(dsm); bool certificatesOk = certs.Count > 0; foreach (X509Certificate cert in certs.Values) { if (CertificateChainVaidationRequired()) { certificatesOk = certificatesOk && VerifyCertificate(cert); } else { certificatesOk = certificatesOk && VerifyAllowedPublicKey(cert); } if (!certificatesOk) { AppHealth.Current.Warning.TrackAsync(StringRes.TemplatePackageValidatePackageCertificatesMessage).FireAndForget(); break; } } return(certificatesOk); }
//<SnippetPackageDigSigValidate> // ------------------------ ValidateSignatures ------------------------ /// <summary> /// Validates all the digital signatures of a given package.</summary> /// <param name="package"> /// The package for validating digital signatures.</param> /// <returns> /// true if all digital signatures are valid; otherwise false if the /// package is unsigned or any of the signatures are invalid.</returns> private static bool ValidateSignatures(Package package) { if (package == null) { throw new ArgumentNullException("ValidateSignatures(package)"); } // Create a PackageDigitalSignatureManager for the given Package. PackageDigitalSignatureManager dsm = new PackageDigitalSignatureManager(package); // Check to see if the package contains any signatures. if (!dsm.IsSigned) { return(false); // The package is not signed. } // Verify that all signatures are valid. VerifyResult result = dsm.VerifySignatures(false); if (result != VerifyResult.Success) { return(false); // One or more digital signatures are invalid. } // else if (result == VerifyResult.Success) return(true); // All signatures are valid. }// end:ValidateSignatures()
public Task <CheckResult> CheckAsync(byte[] buffer) { var file = new MemoryStream(buffer); var result = new CheckResult { Success = true, Errors = new List <string>() }; using (var package = Package.Open(file)) { var dsManager = new PackageDigitalSignatureManager(package); var verifyResult = dsManager.VerifySignatures(false); if (verifyResult != VerifyResult.Success) { result.Success = false; result.Errors.Add(verifyResult.ToString()); } IEnumerable <string> signers = dsManager.Signatures.OfType <PackageDigitalSignature>() .Select(s => ((X509Certificate2)s.Signer).Thumbprint).ToList(); foreach (var signer in signers) { if (!validThumbprints.Contains(signer)) { result.Success = false; result.Errors.Add($"Not valid signer {signer}"); } } } return(Task.FromResult(result)); }
/// <summary> /// Verify. /// </summary> /// <param name="input">The input.</param> /// <param name="serial">The serial.</param> /// <returns></returns> public override bool Verify(Stream input, string serial = null) { if (input == null) { throw new ArgumentNullException("input"); } using (var package = Package.Open(input, FileMode.Open, FileAccess.Read)) { var mgr = new PackageDigitalSignatureManager(package) { CertificateOption = CertificateEmbeddingOption.InSignaturePart }; var result = false; foreach (var sig in mgr.Signatures) { var verifyResult = mgr.VerifySignatures(true); result = verifyResult == VerifyResult.Success; if (result && !String.IsNullOrWhiteSpace(serial)) { var actualSerial = new BigInteger(sig.Signer.GetSerialNumber()); var expectedSerial = CertUtil.HexadecimalStringToBigInt(serial); result = actualSerial == expectedSerial; } } package.Close(); return(result); } }
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(); }
/// <summary> /// Method that remove a signer of the file /// </summary> /// <param name="signer">Name of the signer</param> public void RemoveUniqueSignatureFromFile(Uri siguri, string serialNumber = null) { if (DocumentType.Equals(Types.XpsDocument)) { //To remove the signature we opened XPS like System.IO.Package, //Because the URI is necessary to remove the correct signature xpsDocument.Close(); package = Package.Open(signers.Path, FileMode.Open, FileAccess.ReadWrite); PackageDigitalSignatureManager _signatures = null; _signatures = new PackageDigitalSignatureManager(package); _signatures.CertificateOption = CertificateEmbeddingOption.InSignaturePart; PackageDigitalSignatureManager _assinaturas = null; _assinaturas = new PackageDigitalSignatureManager(base.package); _assinaturas.CertificateOption = CertificateEmbeddingOption.InSignaturePart; _assinaturas.RemoveSignature(siguri); package.Flush(); package.Close(); } else if (DocumentType.Equals(Types.PdfDocument)) { CertificadoDigital.Remove.removeSignature(pdfDocumentPath, serialNumber); } else { PackageDigitalSignatureManager _assinaturas = null; _assinaturas = new PackageDigitalSignatureManager(base.package); _assinaturas.CertificateOption = CertificateEmbeddingOption.InSignaturePart; _assinaturas.RemoveSignature(siguri); package.Flush(); package.Close(); } }
public static PackageDigitalSignature GetSignature(this Package package) { //VALIDATE THAT THE PACKAGE GIVEN IS A SIGNED PARAGON PACKAGE var dsm = new PackageDigitalSignatureManager(package); return(package.IsSigned() ? dsm.Signatures[0] : null); }
public bool DocumentHasSignature(X509Certificate2 certificate) { string signerSerialNumber = certificate.GetSerialNumberString(); string serialNumber = ""; if (DocumentType.Equals(Types.XpsDocument)) { //Search the serial in a Xps signatures. foreach (XpsDigitalSignature signature in xpsDocument.Signatures) { serialNumber = signature.SignerCertificate.GetSerialNumberString(); if (serialNumber == signerSerialNumber) { return(true); } } } else { PackageDigitalSignatureManager _assinaturas = null; _assinaturas = new PackageDigitalSignatureManager(base.package); _assinaturas.CertificateOption = CertificateEmbeddingOption.InSignaturePart; foreach (PackageDigitalSignature signature in _assinaturas.Signatures) { serialNumber = signature.Signer.GetSerialNumberString(); if (serialNumber == signerSerialNumber) { return(true); } } } return(false); }
RemoveSignature( XpsDigitalSignature signature ) { CheckDisposed(); if (null == signature) { throw new ArgumentNullException("signature"); } if (null == signature.PackageSignature) { throw new NullReferenceException("signature.PackageSignature"); } if (null == signature.PackageSignature.SignaturePart) { throw new NullReferenceException("signature.PackageSignature.SignaturePart"); } if (CurrentXpsManager == null) { throw new InvalidOperationException(SR.Get(SRID.ReachPackaging_DocumentWasClosed)); } PackageDigitalSignatureManager packageSignatures = new PackageDigitalSignatureManager(CurrentXpsManager.MetroPackage); packageSignatures.RemoveSignature(signature.PackageSignature.SignaturePart.Uri); _reachSignatures = null; _reachSignatureList = null; EnsureSignatures(); }
public bool VerifySignatures(Package package) { var dsm = new PackageDigitalSignatureManager(package); VerifyResult verifyResult = dsm.VerifySignatures(false); return(verifyResult == VerifyResult.Success); }
/// <summary> /// Tests a Digital Signature from a package /// </summary> /// <returns>Digital signatures list</returns> public static Collection <string> GetList(OpenXmlPowerToolsDocument doc) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { // Creates the PackageDigitalSignatureManager PackageDigitalSignatureManager digitalSignatureManager = new PackageDigitalSignatureManager(streamDoc.GetPackage()); // Verifies the collection of certificates in the package Collection <string> digitalSignatureDescriptions = new Collection <string>(); ReadOnlyCollection <PackageDigitalSignature> digitalSignatures = digitalSignatureManager.Signatures; if (digitalSignatures.Count > 0) { foreach (PackageDigitalSignature signature in digitalSignatures) { if (PackageDigitalSignatureManager.VerifyCertificate(signature.Signer) != X509ChainStatusFlags.NoError) { digitalSignatureDescriptions.Add(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Signature: {0} ({1})", signature.Signer.Subject, PackageDigitalSignatureManager.VerifyCertificate(signature.Signer))); } else { digitalSignatureDescriptions.Add("Signature: " + signature.Signer.Subject); } } } else { digitalSignatureDescriptions.Add("No digital signatures found"); } return(digitalSignatureDescriptions); } }
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()); } }
//------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ /// <summary> /// Parse the Manifest tag /// </summary> /// <param name="manager"></param> /// <param name="reader">XmlReader positioned to the Manifest tag</param> /// <param name="partManifest"></param> /// <param name="partEntryManifest"></param> /// <param name="relationshipManifest"></param> internal static void ParseManifest( PackageDigitalSignatureManager manager, XmlReader reader, out List <Uri> partManifest, out List <PartManifestEntry> partEntryManifest, out List <PackageRelationshipSelector> relationshipManifest) { Invariant.Assert(manager != null); Invariant.Assert(reader != null); // these are empty (non-null) when nothing is found partManifest = new List <Uri>(); partEntryManifest = new List <PartManifestEntry>(); relationshipManifest = new List <PackageRelationshipSelector>(); // manually parse the Relationship tags because they are custom formed and the Reference class will not handle // them correctly string referenceTagName = XTable.Get(XTable.ID.ReferenceTagName); int referenceCount = 0; while (reader.Read() && (reader.MoveToContent() == XmlNodeType.Element)) { // should be on a <Reference> tag if (String.CompareOrdinal(reader.NamespaceURI, SignedXml.XmlDsigNamespaceUrl) == 0 && (String.CompareOrdinal(reader.LocalName, referenceTagName) == 0) && reader.Depth == 2) { // Parse each reference - distinguish between Relationships and Parts // because we don't store the Relationship-part itself - just it's Relationships. PartManifestEntry partManifestEntry = ParseReference(reader); if (partManifestEntry.IsRelationshipEntry) { foreach (PackageRelationshipSelector relationshipSelector in partManifestEntry.RelationshipSelectors) { relationshipManifest.Add(relationshipSelector); } } else { partManifest.Add(partManifestEntry.Uri); } // return the manifest entry to be used for hashing partEntryManifest.Add(partManifestEntry); referenceCount++; } else { throw new XmlException(SR.Get(SRID.UnexpectedXmlTag, reader.Name)); } } // XmlDSig xsd requires at least one <Reference> tag if (referenceCount == 0) { throw new XmlException(SR.Get(SRID.PackageSignatureCorruption)); } }
private static bool VerifyCertificate(X509Certificate cert) { var status = PackageDigitalSignatureManager.VerifyCertificate(cert); AppHealth.Current.Verbose.TrackAsync($"Certificate '{cert.Subject}' verification finished with status '{status.ToString()}'").FireAndForget(); return(status == X509ChainStatusFlags.NoError); }
private static bool VerifyCertificate(X509Certificate cert) { var status = PackageDigitalSignatureManager.VerifyCertificate(cert); AppHealth.Current.Verbose.TrackAsync(string.Format(StringRes.TemplatePackageVerifyCertificateMessage, cert.Subject, status.ToString())).FireAndForget(); return(status == X509ChainStatusFlags.NoError); }
private static bool ValidateSignatures(Package package) { var signatureManager = new PackageDigitalSignatureManager(package); bool isSigned = signatureManager.IsSigned; var verifyResult = signatureManager.VerifySignatures(true); return(isSigned && verifyResult == VerifyResult.Success); }
public static bool IsSigned(string signedPackageFilename) { using (Package package = Package.Open(signedPackageFilename, FileMode.Open, FileAccess.Read, FileShare.Read)) { var dsm = new PackageDigitalSignatureManager(package); return(dsm.IsSigned); } }
/// <summary> /// Return a List of Signer in the package /// </summary> /// <returns> /// Package Path (string), Signer Name (string), Signer URI (string), Signer Issuer (string) /// </returns> public Signers GetDigitalSigners() { Signers sigs = new Signers(); sigs.Path = signers.Path; List <X509Certificate2> certificateList = new List <X509Certificate2>(); List <XmlSignaturePart> xmlSignaturePartList = this.GetDigitalSignatures(); if (DocumentType.Equals(Types.XpsDocument)) { //To collect the information of the signature we used XPS like a System.IO.Packaging xpsDocument.Close(); package = Package.Open(signers.Path, FileMode.Open, FileAccess.Read); PackageDigitalSignatureManager _signatures = null; _signatures = new PackageDigitalSignatureManager(package); _signatures.CertificateOption = CertificateEmbeddingOption.InSignaturePart; // Add the signers in the list foreach (PackageDigitalSignature signature in _signatures.Signatures) { string name = signature.Signer.Subject.Replace("CN=", ""); string uri = signature.SignaturePart.Uri.ToString(); string date = signature.SigningTime.ToString(); string issuer = signature.Signer.Issuer.Replace("CN=", ""); string serial = signature.Signer.GetSerialNumberString(); X509Certificate2 signatureCertificate = (X509Certificate2)signature.Signer; sigs.Add(name, uri, issuer, date, serial, signatureCertificate); } package.Close(); xpsDocument = new XpsDocument(signers.Path, FileAccess.ReadWrite); return(sigs); } else { PackageDigitalSignatureManager _signatures = null; _signatures = new PackageDigitalSignatureManager(package); _signatures.CertificateOption = CertificateEmbeddingOption.InSignaturePart; // Add the signers in the list foreach (PackageDigitalSignature signature in _signatures.Signatures) { string name = signature.Signer.Subject.Replace("CN=", ""); string uri = signature.SignaturePart.Uri.ToString(); string date = signature.SigningTime.ToString(); string issuer = signature.Signer.Issuer.Replace("CN=", ""); string serial = signature.Signer.GetSerialNumberString(); X509Certificate2 signatureCertificate = (X509Certificate2)signature.Signer; sigs.Add(name, uri, issuer, date, serial, signatureCertificate); } return(sigs); } }
//------------------------------------------------------ // // Private Methods // //------------------------------------------------------ /// <summary> /// GenerateRelationshipSigningReferences /// </summary> /// <param name="manager"></param> /// <param name="xDoc"></param> /// <param name="hashAlgorithm"></param> /// <param name="relationshipSelectors"></param> /// <param name="manifest"></param> /// <returns>number of references to be signed</returns> private static int GenerateRelationshipSigningReferences( PackageDigitalSignatureManager manager, XmlDocument xDoc, HashAlgorithm hashAlgorithm, IEnumerable <PackageRelationshipSelector> relationshipSelectors, XmlNode manifest) { // PartUri - and its list of PackageRelationshipSelectors Dictionary <Uri, List <PackageRelationshipSelector> > partAndSelectorDictionary = new Dictionary <Uri, List <PackageRelationshipSelector> >(); foreach (PackageRelationshipSelector relationshipSelector in relationshipSelectors) { //update the partAndSelectorDictionary for each relationshipSelector Uri relationshipPartUri = PackUriHelper.GetRelationshipPartUri(relationshipSelector.SourceUri); List <PackageRelationshipSelector> selectors; if (partAndSelectorDictionary.ContainsKey(relationshipPartUri)) { selectors = partAndSelectorDictionary[relationshipPartUri]; } else { selectors = new List <PackageRelationshipSelector>(); partAndSelectorDictionary.Add(relationshipPartUri, selectors); } selectors.Add(relationshipSelector); } // now that we have them grouped by Part name, emit the XML // Here is an optimization for saving space by declaring the OPC namespace and prefix // in the <Manifest> tag. It will become: // <Manifest xmlns:opc="http://schemas.openxmlformats.org/package/2006/digital-signature"> // Later when we generate the RelationshipSigningReference we can use the namespace prefix "opc" // instead of the long namespace itself, thus saving some space if the manifest has more than one // RelationshipSigningReference. // XmlElement xmlE = (XmlElement)manifest; xmlE.SetAttribute(XTable.Get(XTable.ID.OpcSignatureNamespaceAttribute), XTable.Get(XTable.ID.OpcSignatureNamespace)); int count = 0; foreach (Uri partName in partAndSelectorDictionary.Keys) { // emit xml and append manifest.AppendChild( GenerateRelationshipSigningReference(manager, xDoc, hashAlgorithm, partName, /* we are guaranteed that this is a valid part Uri, so we do not use PackUriHelper.CreatePartUri */ partAndSelectorDictionary[partName])); count++; } return(count); }
public static bool IsSigned(this Package package) { //VALIDATE THAT THE PACKAGE GIVEN IS A SIGNED PARAGON PACKAGE var dsm = new PackageDigitalSignatureManager(package); var innerPackageName = GetInnerPackageName(); var uriString = "/" + innerPackageName + ".pgx"; var uri = new Uri(uriString, UriKind.Relative); return(package.PartExists(uri) && dsm.Signatures.Count == 1); }
public static VerifyResult VerifySignature(OpenXmlPackage openXmlPackage) { if (openXmlPackage == null) { throw new ArgumentNullException(nameof(openXmlPackage)); } var dsm = new PackageDigitalSignatureManager(openXmlPackage.Package); return(dsm.VerifySignatures(true)); }
private static XmlNode GenerateDigestMethod( PackageDigitalSignatureManager manager, XmlDocument xDoc) { // <DigestMethod> XmlElement digestMethod = xDoc.CreateElement(XTable.Get(XTable.ID.DigestMethodTagName), SignedXml.XmlDsigNamespaceUrl); XmlAttribute digestAlgorithmAttr = xDoc.CreateAttribute(XTable.Get(XTable.ID.AlgorithmAttrName)); digestAlgorithmAttr.Value = manager.HashAlgorithm; digestMethod.Attributes.Append(digestAlgorithmAttr); return(digestMethod); }
}// end:ValidateSignatures() //</SnippetPackageDigSigValidate> //<SnippetPackageDigSigSign> 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); } }// end:SignAllParts()
/// <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); }// end:SignAllParts()
public Uri GetSignatureOriginUri() { PackageDigitalSignatureManager manager = new PackageDigitalSignatureManager(this._metroPackage); return manager.SignatureOrigin; }
public PackageDigitalSignature Sign(IEnumerable<Uri> partList, X509Certificate certificate, bool embedCertificate, IEnumerable<PackageRelationshipSelector> relationshipSelectors, string id) { if (this._metroPackage == null) { throw new ObjectDisposedException("XpsManager"); } PackageDigitalSignatureManager manager = new PackageDigitalSignatureManager(this._metroPackage); if (embedCertificate) { manager.CertificateOption = CertificateEmbeddingOption.InCertificatePart; } else { manager.CertificateOption = CertificateEmbeddingOption.NotEmbedded; } if (id != null) { return manager.Sign(partList, certificate, relationshipSelectors, id); } return manager.Sign(partList, certificate, relationshipSelectors); }
private void EnsureSignatures() { if (this._reachSignatures == null) { this._reachSignatures = new Collection<XpsDigitalSignature>(); PackageDigitalSignatureManager manager = new PackageDigitalSignatureManager(base.CurrentXpsManager.MetroPackage); foreach (PackageDigitalSignature signature in manager.Signatures) { XpsDigitalSignature item = new XpsDigitalSignature(signature, this); if (item.SignedDocumentSequence != null) { this._reachSignatures.Add(item); } } } }