static void Main(string[] args) { X509Certificate2 x509Certificate2 = GetCertificate("990B25F50DC7E2B548BE75AFED579448"); //X509Certificate2 x509Certificate2 = GetCertificate("0efb7eebdcda4f64a718db3ff908b085"); //X509Certificate2 x509Certificate2 = GetCertificate("2E0A6058EA90DB8C46D1FD3513A877F8"); DCinemaSecurityMessageType extraTheatreMessage = new DCinemaSecurityMessageType(); XmlSerializer xmlSerializer = new XmlSerializer(extraTheatreMessage.GetType()); extraTheatreMessage.AuthenticatedPublic = new AuthenticatedPublicType(); extraTheatreMessage.AuthenticatedPublic.Id = "AuthenticatedPublic.Id." + Guid.NewGuid().ToString(); extraTheatreMessage.AuthenticatedPublic.MessageId = "urn:uuid:" + Guid.NewGuid().ToString(); extraTheatreMessage.AuthenticatedPublic.MessageType = "http://www.smpte-ra.org/schemas/430-3/2006/ETM"; extraTheatreMessage.AuthenticatedPublic.AnnotationText = new UserText(); extraTheatreMessage.AuthenticatedPublic.AnnotationText.Value = "Empty Extra-Theatre Message"; extraTheatreMessage.AuthenticatedPublic.AnnotationText.language = "en-us"; extraTheatreMessage.AuthenticatedPublic.IssueDate = DateTime.Now; X509IssuerSerial issuerSerial = new X509IssuerSerial(); issuerSerial.IssuerName = x509Certificate2.IssuerName.Name; issuerSerial.SerialNumber = x509Certificate2.SerialNumber; extraTheatreMessage.AuthenticatedPublic.Signer = issuerSerial; extraTheatreMessage.AuthenticatedPrivate = new AuthenticatedPrivateType(); extraTheatreMessage.AuthenticatedPrivate.Id = "AuthenticatedPrivate.Id." + Guid.NewGuid().ToString(); #region Build the signature elements SignedXml signedXml = null; try { signedXml = new SignedXml(); signedXml.SigningKey = x509Certificate2.PrivateKey; //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/ 2001/04/xmldsig-more#rsasha256"; //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; StringWriter stringWriter = new StringWriter(); xmlSerializer.Serialize(stringWriter, extraTheatreMessage); string serializedXML = stringWriter.ToString(); #region Build the AuthenticatedPublic DataObject & Reference string xmlAuthenticatedPublic = GetCleanElement(serializedXML, "AuthenticatedPublic"); XmlDocument docAuthenticatedPublic = new XmlDocument(); docAuthenticatedPublic.LoadXml(xmlAuthenticatedPublic.ToString()); //XmlAttribute attrAuthenticatedPublic = docAuthenticatedPublic.CreateAttribute("xmlns"); //attrAuthenticatedPublic.Value = "http://www.smpte-ra.org/schemas/430-3/2006/ETM"; //docAuthenticatedPublic.DocumentElement.Attributes.Append(attrAuthenticatedPublic); DataObject dataObjectAuthenticatedPublic = new DataObject("AuthenticatedPublic", "", "", docAuthenticatedPublic.DocumentElement); //DataObject dataObjectAuthenticatedPublic = new DataObject(); dataObjectAuthenticatedPublic.Data = docAuthenticatedPublic.ChildNodes; dataObjectAuthenticatedPublic.Id = "AuthenticatedPublic"; signedXml.AddObject(dataObjectAuthenticatedPublic); Reference referenceAuthenticatedPublic = new Reference(); referenceAuthenticatedPublic.Uri = "#AuthenticatedPublic"; referenceAuthenticatedPublic.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; signedXml.AddReference(referenceAuthenticatedPublic); #endregion #region Build the AuthenticatedPublic DataObject & Reference string xmlAuthenticatedPrivate = GetCleanElement(serializedXML, "AuthenticatedPrivate"); XmlDocument docAuthenticatedPrivate = new XmlDocument(); docAuthenticatedPrivate.LoadXml(xmlAuthenticatedPrivate.ToString()); //XmlAttribute attrAuthenticatedPrivate = docAuthenticatedPrivate.CreateAttribute("xmlns"); //attrAuthenticatedPrivate.Value = "http://www.smpte-ra.org/schemas/430-3/2006/FLM"; //docAuthenticatedPrivate.DocumentElement.Attributes.Append(attrAuthenticatedPrivate); DataObject dataObjectAuthenticatedPrivate = new DataObject("AuthenticatedPrivate", "", "", docAuthenticatedPrivate.DocumentElement); //DataObject dataObjectAuthenticatedPrivate = new DataObject("AuthenticatedPrivate", "", "", docAuthenticatedPrivate.DocumentElement); //dataObjectAuthenticatedPrivate.Data = docAuthenticatedPrivate.ChildNodes; //dataObjectAuthenticatedPrivate.Id = "AuthenticatedPrivate"; signedXml.AddObject(dataObjectAuthenticatedPrivate); Reference referenceAuthenticatedPrivate = new Reference(); referenceAuthenticatedPrivate.Uri = "#AuthenticatedPrivate"; referenceAuthenticatedPrivate.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; // Add the reference to the message. signedXml.AddReference(referenceAuthenticatedPrivate); #endregion // Add a KeyInfo. KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(x509Certificate2, X509IncludeOption.WholeChain)); signedXml.KeyInfo = keyInfo; // Compute the signature. signedXml.ComputeSignature(); XmlElement singedElement = signedXml.GetXml(); XmlSerializer signedSerializer = new XmlSerializer(singedElement.GetType()); StreamWriter signedWriter = new StreamWriter("D:\\signedSerializer.Test.xml"); signedSerializer.Serialize(signedWriter, singedElement); signedWriter.Close(); } catch (CryptographicException e) { Console.WriteLine(e.Message); } #endregion #region Fill in the signature element extraTheatreMessage.Signature = signedXml.Signature.GetXml(); #endregion xmlSerializer.Serialize(Console.Out, extraTheatreMessage); Console.WriteLine("\r\n"); TextWriter WriteFileStream = new StreamWriter(@"\Source_SMPTE\Output\ExtraTheatreMessage.xml"); xmlSerializer.Serialize(WriteFileStream, extraTheatreMessage); WriteFileStream.Close(); ServiceExtraTheatreMessageClient client = new ServiceExtraTheatreMessageClient(); string response = client.ETM(extraTheatreMessage); DCinemaSecurityMessageType existingETM = new DCinemaSecurityMessageType(); TextReader readFileStream = new StreamReader(@"\Source_SMPTE\Input\DCinemaSecurityMessageType_AMC.xml"); existingETM = (DCinemaSecurityMessageType)xmlSerializer.Deserialize(readFileStream); readFileStream.Close(); existingETM.AuthenticatedPrivate = new AuthenticatedPrivateType(); existingETM.Signature = signedXml.Signature.GetXml(); WriteFileStream = new StreamWriter(@"\Source_SMPTE\Output\Read_ExtraTheatreMessage.xml"); xmlSerializer.Serialize(WriteFileStream, existingETM); WriteFileStream.Close(); response = client.ETM(existingETM); }
/// <summary> /// Inserta un contenido XML para generar una firma enveloping. /// </summary> /// <param name="xmlDocument"></param> private void SetContentEveloping(SignatureDocument sigDocument, XmlDocument xmlDocument) { _refContent = new Reference(); sigDocument.XadesSignature = new XadesSignedXml(); XmlDocument doc = (XmlDocument)xmlDocument.Clone(); doc.PreserveWhitespace = true; if (doc.ChildNodes[0].NodeType == XmlNodeType.XmlDeclaration) { doc.RemoveChild(doc.ChildNodes[0]); } //Add an object string dataObjectId = "DataObject-" + Guid.NewGuid().ToString(); System.Security.Cryptography.Xml.DataObject dataObject = new System.Security.Cryptography.Xml.DataObject(); dataObject.Data = doc.ChildNodes; dataObject.Id = dataObjectId; sigDocument.XadesSignature.AddObject(dataObject); _refContent.Id = "Reference-" + Guid.NewGuid().ToString(); _refContent.Uri = "#" + dataObjectId; _refContent.Type = XadesSignedXml.XmlDsigObjectType; XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); _refContent.AddTransform(transform); sigDocument.XadesSignature.AddReference(_refContent); }
public void NewDataObject () { string test = "<Test>DataObject</Test>"; XmlDocument doc = new XmlDocument (); doc.LoadXml (test); DataObject obj1 = new DataObject (); Assert.IsTrue ((obj1.Data.Count == 0), "Data.Count==0"); Assert.AreEqual ("<Object xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", (obj1.GetXml ().OuterXml), "Just constructed"); obj1.Id = "id"; obj1.MimeType = "mime"; obj1.Encoding = "encoding"; Assert.AreEqual ("<Object Id=\"id\" MimeType=\"mime\" Encoding=\"encoding\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", (obj1.GetXml ().OuterXml), "Only attributes"); obj1.Data = doc.ChildNodes; Assert.IsTrue ((obj1.Data.Count == 1), "Data.Count==1"); XmlElement xel = obj1.GetXml (); DataObject obj2 = new DataObject (); obj2.LoadXml (xel); Assert.AreEqual ((obj1.GetXml ().OuterXml), (obj2.GetXml ().OuterXml), "obj1==obj2"); DataObject obj3 = new DataObject (obj1.Id, obj1.MimeType, obj1.Encoding, doc.DocumentElement); Assert.AreEqual ((obj2.GetXml ().OuterXml), (obj3.GetXml ().OuterXml), "obj2==obj3"); }
/// <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 }); } } }
private static DataObject CreateMetaDataObject(long uniqueId, string reason) { /* * This parts can be modified, currently only 2 meta objects are added (unique tag is never used) */ //https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2.import?view=netframework-4.8 //Should add a sign with it also so that it can be proven that data is not tempered and should add verifire for it also DataObject dataObject = new DataObject(); XmlDocument xmlDoc = new XmlDocument(); XmlNode root = xmlDoc.AppendChild(xmlDoc.CreateElement("meta", "meta-data")); XmlNode child1 = root.AppendChild(xmlDoc.CreateElement("unique", "base64-desktop-pc-time")); //XmlAttribute childAtt1 = child1.Attributes.Append(xmlDoc.CreateAttribute("server-unique")); //childAtt1.InnerText = uniqueId.ToString(); child1.InnerText = Base64EncodedCurrentTime(null); XmlNode child2 = root.AppendChild(xmlDoc.CreateElement("signing-reason", "signing-local-time")); XmlAttribute childAtt2 = child2.Attributes.Append(xmlDoc.CreateAttribute("local-time")); childAtt2.InnerText = DateTime.UtcNow.ToString(); //Local Time child2.InnerText = reason; //Server Time //Sign Meta Data and store without key //xmlDoc = GetSignedMetaData(xmlDoc, certificate); dataObject.Data = xmlDoc.ChildNodes; dataObject.Id = uniqueId.ToString();// new Random().Next().ToString(); return(dataObject); }
private static void SignAllParts(Package package, X509Certificate certificate) { List <Uri> PartstobeSigned = new List <Uri>(); List <PackageRelationshipSelector> SignableReleationships = new List <PackageRelationshipSelector>(); foreach (PackageRelationship relationship in package.GetRelationshipsByType(RT_OfficeDocument)) { // Pass the releationship of the root. This is decided based on the RT_OfficeDocument // http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument CreateListOfSignableItems(relationship, PartstobeSigned, SignableReleationships); } // Create the DigitalSignature Manager PackageDigitalSignatureManager dsm = new PackageDigitalSignatureManager(package); dsm.CertificateOption = CertificateEmbeddingOption.InSignaturePart; dsm.HashAlgorithm = ManifestHashAlgorithm; try { System.Security.Cryptography.Xml.DataObject officeObject = CreateOfficeObject(SignatureID, dsm.HashAlgorithm); Reference officeObjectReference = new Reference("#" + OfficeObjectID); var sgn = dsm.Sign(PartstobeSigned, certificate, SignableReleationships, SignatureID, new System.Security.Cryptography.Xml.DataObject[] { officeObject }, new Reference[] { officeObjectReference }); } catch (CryptographicException ex) { Console.WriteLine(ex.InnerException.ToString()); } }
/// <summary> /// Method that return the Object for fixing validation problem /// </summary> /// <param name="SignatureID">ID of Signature</param> /// <param name="ManifestHashAlgorithm">Hash Algorithm</param> /// <returns>DataObject</returns> private System.Security.Cryptography.Xml.DataObject CreateOfficeObject(string SignatureID, string ManifestHashAlgorithm) { XmlDocument document = new XmlDocument(); document.LoadXml(String.Format(officeDocument, SignatureID, ManifestHashAlgorithm)); System.Security.Cryptography.Xml.DataObject officeObject = new System.Security.Cryptography.Xml.DataObject(); // do not change the order of the following two lines officeObject.LoadXml(document.DocumentElement); // resets ID officeObject.Id = OfficeObjectID; // required ID, do not change return(officeObject); }
public static string SignXMLX509Data(string strXML) { string strResult = ""; try { SignedXml signedXml = new SignedXml(); // Get the signature key. For this demo, we look for keys associated with a certificate in the "MY" store RSACryptoServiceProvider rsa = null; X509Certificate x509Cert = null; GetSignatureKey(out rsa, out x509Cert); if (rsa == null) { return(""); } signedXml.SigningKey = rsa; Reference reference = new Reference(); reference.Uri = "#object-1"; reference.Type = "http://www.w3.org/2000/09/xmldsig#Object"; // Add an object System.Security.Cryptography.Xml.DataObject obj = new System.Security.Cryptography.Xml.DataObject(); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(strXML); obj.Data = doc.ChildNodes; obj.Id = "object-1"; signedXml.AddObject(obj); signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); // Include the certificate raw data with the signed file keyInfo.AddClause(new KeyInfoX509Data(x509Cert)); signedXml.KeyInfo = keyInfo; // compute the signature signedXml.ComputeSignature(); strResult = signedXml.GetXml().OuterXml; } catch (Exception exc) { MessageBox.Show(exc.ToString(), Messages.ExceptionTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop); return(strResult); } return(strResult); }
public static void SignXmlDocument(Stream sourceXmlFile, Stream destinationXmlFile, X509Certificate2 certificate) { // Carico il documento XML XmlDocument doc = new XmlDocument(); doc.Load(sourceXmlFile); // Preparo un DOMDocument che conterrà il risultato XmlDocument outputDocument = new XmlDocument(); // Recupero un riferimento all'intero contenuto del documento XML XmlNodeList elementsToSign = doc.SelectNodes(String.Format("/{0}", doc.DocumentElement.Name)); // Costruisco la firma SignedXml signedXml = new SignedXml(); System.Security.Cryptography.Xml.DataObject dataSignature = new System.Security.Cryptography.Xml.DataObject { Data = elementsToSign, Id = doc.DocumentElement.Name }; signedXml.AddObject(dataSignature); Reference reference = new Reference { Uri = String.Format("#{0}", dataSignature.Id) }; signedXml.AddReference(reference); if ((certificate != null) && (certificate.HasPrivateKey)) { signedXml.SigningKey = certificate.PrivateKey; KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificate)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); // Aggiungo la firma al nuovo documento di output outputDocument.AppendChild( outputDocument.ImportNode(signedXml.GetXml(), true)); outputDocument.Save(destinationXmlFile); } }
public override string SignXml(XmlDocument Document) { SignedXmlWithId signedXml = new SignedXmlWithId(Document); signedXml.SigningKey = manager.Certificate.PrivateKey; KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(manager.Certificate); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; // the DataObject has to point to a XmlNodeList DataObject dataObject = new DataObject(); dataObject.Id = "MyObjectID1"; dataObject.Data = new CustomXmlNodeList(new[] { Document.DocumentElement }); signedXml.AddObject(dataObject); // Add the reference to the SignedXml object. Reference reference = new Reference(); reference.Uri = "#MyObjectID1"; signedXml.AddReference(reference); // Create a reference to be signed. if (c14) { XmlDsigC14NTransform env = new XmlDsigC14NTransform(); reference.AddTransform(env); } // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); // create detached envelope XmlDocument envelope = new XmlDocument(); envelope.AppendChild(envelope.CreateElement("Envelope")); envelope.DocumentElement.AppendChild( envelope.ImportNode(xmlDigitalSignature, true)); return envelope.OuterXml; }
public void ImportDataObject () { string value1 = "<Object Id=\"id\" MimeType=\"mime\" Encoding=\"encoding\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><Test xmlns=\"\">DataObject1</Test><Test xmlns=\"\">DataObject2</Test></Object>"; XmlDocument doc = new XmlDocument (); doc.LoadXml (value1); DataObject obj1 = new DataObject (); obj1.LoadXml (doc.DocumentElement); Assert.IsTrue ((obj1.Data.Count == 2), "Data.Count==2"); string s = (obj1.GetXml ().OuterXml); Assert.AreEqual (value1, s, "DataObject 1"); string value2 = "<Object xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><Test xmlns=\"\" /></Object>"; doc = new XmlDocument (); doc.LoadXml (value2); DataObject obj2 = new DataObject (); obj2.LoadXml (doc.DocumentElement); s = (obj2.GetXml ().OuterXml); Assert.AreEqual (value2, s, "DataObject 2"); string value3 = "<Object Id=\"id\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><Test xmlns=\"\" /></Object>"; doc = new XmlDocument (); doc.LoadXml (value3); DataObject obj3 = new DataObject (); obj3.LoadXml (doc.DocumentElement); s = (obj3.GetXml ().OuterXml); Assert.AreEqual (value3, s, "DataObject 3"); string value4 = "<Object MimeType=\"mime\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><Test xmlns=\"\" /></Object>"; doc = new XmlDocument (); doc.LoadXml (value4); DataObject obj4 = new DataObject (); obj4.LoadXml (doc.DocumentElement); s = (obj4.GetXml ().OuterXml); Assert.AreEqual (value4, s, "DataObject 4"); }
public static void SignXmlDocument(Stream sourceXmlFile, Stream destinationXmlFile, X509Certificate2 certificate) { // Carico il documento XML XmlDocument doc = new XmlDocument(); doc.Load(sourceXmlFile); // Preparo un DOMDocument che conterrà il risultato XmlDocument outputDocument = new XmlDocument(); // Recupero un riferimento all'intero contenuto del documento XML XmlNodeList elementsToSign = doc.SelectNodes(String.Format("/{0}", doc.DocumentElement.Name)); // Costruisco la firma SignedXml signedXml = new SignedXml(); System.Security.Cryptography.Xml.DataObject dataSignature = new System.Security.Cryptography.Xml.DataObject(); dataSignature.Data = elementsToSign; dataSignature.Id = doc.DocumentElement.Name; signedXml.AddObject(dataSignature); Reference reference = new Reference(); reference.Uri = String.Format("#{0}", dataSignature.Id); signedXml.AddReference(reference); if ((certificate != null) && (certificate.HasPrivateKey)) { signedXml.SigningKey = certificate.PrivateKey; KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificate)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); // Aggiungo la firma al nuovo documento di output outputDocument.AppendChild( outputDocument.ImportNode(signedXml.GetXml(), true)); outputDocument.Save(destinationXmlFile); } }
/// <summary> /// Inserta un contenido XML para generar una firma enveloping. /// </summary> /// <param name="xmlDocument"></param> public void SetContentEveloping(XmlDocument xmlDocument) { Reference reference = new Reference(); _xadesSignedXml = new XadesSignedXml(); XmlDocument doc = (XmlDocument)xmlDocument.Clone(); doc.PreserveWhitespace = true; if (doc.ChildNodes[0].NodeType == XmlNodeType.XmlDeclaration) { doc.RemoveChild(doc.ChildNodes[0]); } //Add an object string dataObjectId = "DataObject-" + Guid.NewGuid().ToString(); System.Security.Cryptography.Xml.DataObject dataObject = new System.Security.Cryptography.Xml.DataObject(); dataObject.Data = doc.ChildNodes; dataObject.Id = dataObjectId; _xadesSignedXml.AddObject(dataObject); reference.Id = "Reference-" + Guid.NewGuid().ToString(); reference.Uri = "#" + dataObjectId; reference.Type = SignedXml.XmlDsigNamespaceUrl + "Object"; XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); reference.AddTransform(transform); _objectReference = reference.Id; _mimeType = "text/xml"; _xadesSignedXml.AddReference(reference); _document = null; }
static System.Security.Cryptography.Xml.DataObject CreateOfficeObject( string signatureID, string manifestHashAlgorithm) { XmlDocument document = new XmlDocument(); document.LoadXml(String.Format( "<OfficeObject>" + "<SignatureProperties xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" + "<SignatureProperty Id=\"idOfficeV1Details\" Target=\"{0}\">" + "<SignatureInfoV1 xmlns=\"http://schemas.microsoft.com/office/2006/digsig\">" + "<SetupID></SetupID>" + "<ManifestHashAlgorithm>{1}</ManifestHashAlgorithm>" + "<SignatureProviderId>{2}</SignatureProviderId>" + "</SignatureInfoV1>" + "</SignatureProperty>" + "</SignatureProperties>" + "</OfficeObject>", signatureID, manifestHashAlgorithm, "{F5AC7D23-DA04-45F5-ABCB-38CE7A982553}")); System.Security.Cryptography.Xml.DataObject officeObject = new System.Security.Cryptography.Xml.DataObject(); // do not change the order of the following two lines officeObject.LoadXml(document.DocumentElement); // resets ID officeObject.Id = OfficeObjectID; // required ID, do not change return(officeObject); }
public void InvalidDataObject3 () { DataObject obj1 = new DataObject (); // seems this isn't invalid !?! // but no exception is thrown string value = "<Test>Bad</Test>"; XmlDocument doc = new XmlDocument (); doc.LoadXml (value); obj1.LoadXml (doc.DocumentElement); string s = (obj1.GetXml ().OuterXml); Assert.AreEqual (value, s, "DataObject Bad"); }
public void InvalidDataObject2 () { DataObject obj1 = new DataObject (); obj1.LoadXml (null); }
public void AddObject(DataObject dataObject) { this.m_signature.AddObject(dataObject); }
public void AddObject(DataObject dataObject) { _embeddedObjects.Add(dataObject); }
/// <summary> /// Sign this information card and write it to a file. /// </summary> /// <param name="filename">Path to where this card should be stored.</param> /// <param name="cert">Certificate to use for signing this card.</param> public void SerializeAndSign( string filename, X509Certificate2 cert ) { MemoryStream stream = new MemoryStream(); XmlWriter writer = XmlWriter.Create( stream ); writer.WriteStartElement( XmlNames.WSIdentity.InfoCardElement, XmlNames.WSIdentity.Namespace ); // // write the InformationCardReference element // writer.WriteAttributeString( XmlNames.Xml.Language, XmlNames.Xml.Namespace, m_language ); writer.WriteStartElement( XmlNames.WSIdentity.InfoCardRefElement, XmlNames.WSIdentity.Namespace ); writer.WriteElementString( XmlNames.WSIdentity.CardIdElement, XmlNames.WSIdentity.Namespace, m_cardId ); writer.WriteElementString( XmlNames.WSIdentity.CardVersionElement, XmlNames.WSIdentity.Namespace, m_cardVersion ); writer.WriteEndElement(); // // card name // if( !String.IsNullOrEmpty( m_cardName ) ) { writer.WriteStartElement( XmlNames.WSIdentity.CardNameElement, XmlNames.WSIdentity.Namespace ); writer.WriteString( m_cardName ); writer.WriteEndElement(); } // // card image // if( null != m_logo && 0 != m_logo.Length ) { writer.WriteStartElement( XmlNames.WSIdentity.CardImageElement, XmlNames.WSIdentity.Namespace ); if( !String.IsNullOrEmpty( m_mimeType ) ) { writer.WriteAttributeString( XmlNames.WSIdentity.MimeTypeAttribute, m_mimeType ); } string val = Convert.ToBase64String( m_logo ); writer.WriteString( val ); writer.WriteEndElement(); } // // card issuer uri // writer.WriteStartElement( XmlNames.WSIdentity.IssuerElement, XmlNames.WSIdentity.Namespace ); writer.WriteString( m_issuerId ); writer.WriteEndElement(); // // issue time // writer.WriteStartElement( XmlNames.WSIdentity.TimeIssuedElement, XmlNames.WSIdentity.Namespace ); writer.WriteString( XmlConvert.ToString( m_issuedOn, XmlDateTimeSerializationMode.Utc ) ); writer.WriteEndElement(); // // expiry time // writer.WriteStartElement( XmlNames.WSIdentity.TimeExpiresElement, XmlNames.WSIdentity.Namespace ); writer.WriteString( XmlConvert.ToString( m_expiresOn, XmlDateTimeSerializationMode.Utc ) ); writer.WriteEndElement(); // // Start the tokenservice list // writer.WriteStartElement( XmlNames.WSIdentity.TokenServiceListElement, XmlNames.WSIdentity.Namespace ); EndpointAddressBuilder eprBuilder = new EndpointAddressBuilder(); eprBuilder.Uri = new Uri( m_issuerId ); eprBuilder.Identity = new X509CertificateEndpointIdentity( cert ); if( null != m_mexUri ) { MetadataReference mexRef = new MetadataReference(); mexRef.Address = new EndpointAddress( m_mexUri ); mexRef.AddressVersion = AddressingVersion.WSAddressing10; MetadataSection mexSection = new MetadataSection(); mexSection.Metadata = mexRef; MetadataSet mexSet = new MetadataSet(); mexSet.MetadataSections.Add( mexSection ); MemoryStream memStream = new MemoryStream(); XmlTextWriter writer1 = new XmlTextWriter( memStream, System.Text.Encoding.UTF8 ); mexSet.WriteTo( writer1 ); writer1.Flush(); memStream.Seek( 0, SeekOrigin.Begin ); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader( memStream, XmlDictionaryReaderQuotas.Max ); eprBuilder.SetMetadataReader( reader ); } m_epr = eprBuilder.ToEndpointAddress(); writer.WriteStartElement( XmlNames.WSIdentity.TokenServiceElement, XmlNames.WSIdentity.Namespace ); // // Write the EndPointReference // m_epr.WriteTo( AddressingVersion.WSAddressing10, writer ); // // Write the UserCredential Element // writer.WriteStartElement( XmlNames.WSIdentity.UserCredentialElement, XmlNames.WSIdentity.Namespace ); // // Write the hint // if( !String.IsNullOrEmpty( m_hint ) ) { writer.WriteStartElement( XmlNames.WSIdentity.DisplayCredentialHintElement, XmlNames.WSIdentity.Namespace ); writer.WriteString( m_hint ); writer.WriteEndElement(); } switch( m_cardType ) { case DefaultValues.CardType.UserNamePassword: writer.WriteStartElement( XmlNames.WSIdentity.UserNamePasswordCredentialElement, XmlNames.WSIdentity.Namespace ); if( !string.IsNullOrEmpty( m_credentialIdentifier ) ) { writer.WriteStartElement( XmlNames.WSIdentity.UserNameElement, XmlNames.WSIdentity.Namespace ); writer.WriteString( m_credentialIdentifier ); writer.WriteEndElement(); } writer.WriteEndElement(); break; case DefaultValues.CardType.KerberosAuth: writer.WriteStartElement( XmlNames.WSIdentity.KerberosV5CredentialElement, XmlNames.WSIdentity.Namespace ); writer.WriteEndElement(); break; case DefaultValues.CardType.SelfIssuedAuth: writer.WriteStartElement( XmlNames.WSIdentity.SelfIssuedCredentialElement, XmlNames.WSIdentity.Namespace ); if( !string.IsNullOrEmpty( m_credentialIdentifier ) ) { writer.WriteStartElement( XmlNames.WSIdentity.PrivatePersonalIdentifierElement, XmlNames.WSIdentity.Namespace ); writer.WriteString( m_credentialIdentifier ); writer.WriteEndElement(); } else { throw new InvalidDataException( "No PPID was specified" ); } writer.WriteEndElement(); break; case DefaultValues.CardType.SmartCard: writer.WriteStartElement( XmlNames.WSIdentity.X509V3CredentialElement, XmlNames.WSIdentity.Namespace ); writer.WriteStartElement( XmlNames.XmlDSig.X509DataElement, XmlNames.XmlDSig.Namespace ); if( !string.IsNullOrEmpty( m_credentialIdentifier ) ) { writer.WriteStartElement( XmlNames.WSSecurityExt.KeyIdentifierElement, XmlNames.WSSecurityExt.Namespace ); writer.WriteAttributeString( XmlNames.WSSecurityExt.ValueTypeAttribute, null, XmlNames.WSSecurityExt.Sha1ThumbrpintKeyTypeValue ); writer.WriteString( m_credentialIdentifier ); writer.WriteEndElement(); } else { throw new InvalidDataException( "No thumbprint was specified" ); } writer.WriteEndElement(); writer.WriteEndElement(); break; default: break; } writer.WriteEndElement(); //end of user credential writer.WriteEndElement(); // end of tokenservice writer.WriteEndElement(); //end of tokenservice list // // tokentypes // writer.WriteStartElement( XmlNames.WSIdentity.SupportedTokenTypeListElement, XmlNames.WSIdentity.Namespace ); foreach( string type in m_tokenTypes ) { writer.WriteElementString( XmlNames.WSTrust.TokenType, XmlNames.WSTrust.Namespace, type ); } writer.WriteEndElement(); // // claims // writer.WriteStartElement( XmlNames.WSIdentity.SupportedClaimTypeListElement, XmlNames.WSIdentity.Namespace ); foreach( ClaimInfo clm in m_supportedClaims ) { writer.WriteStartElement( XmlNames.WSIdentity.SupportedClaimTypeElement, XmlNames.WSIdentity.Namespace ); writer.WriteAttributeString( XmlNames.WSIdentity.UriAttribute, clm.Id ); if( !String.IsNullOrEmpty( clm.DisplayTag ) ) { writer.WriteElementString( XmlNames.WSIdentity.DisplayTagElement, XmlNames.WSIdentity.Namespace, clm.DisplayTag ); } if( !String.IsNullOrEmpty( clm.Description ) ) { writer.WriteElementString( XmlNames.WSIdentity.DescriptionElement, XmlNames.WSIdentity.Namespace, clm.Description ); } writer.WriteEndElement(); } writer.WriteEndElement(); // // RequireAppliesTo // if( m_requireAppliesTo ) { writer.WriteElementString( XmlNames.WSIdentity.RequireAppliesToElement, XmlNames.WSIdentity.Namespace, null ); } // // Privacy Notice // if( !String.IsNullOrEmpty( m_privacyNoticeAt ) ) { writer.WriteStartElement( XmlNames.WSIdentity.PrivacyNoticeAtElement, XmlNames.WSIdentity.Namespace ); writer.WriteString( m_privacyNoticeAt ); writer.WriteEndElement(); } writer.WriteEndElement(); writer.Close(); // // Sign the xml content // stream.Position = 0; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = false; doc.Load( stream ); SignedXml signed = new SignedXml(); signed.SigningKey = cert.PrivateKey; signed.Signature.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; Reference reference = new Reference(); reference.Uri = "#_Object_InfoCard"; reference.AddTransform( new XmlDsigExcC14NTransform() ); signed.AddReference( reference ); KeyInfo info = new KeyInfo(); KeyInfoX509Data data = new KeyInfoX509Data( cert, X509IncludeOption.WholeChain ); info.AddClause( data ); signed.KeyInfo = info; DataObject cardData = new DataObject( "_Object_InfoCard", null, null, doc.DocumentElement ); signed.AddObject( cardData ); signed.ComputeSignature(); XmlElement e = signed.GetXml(); XmlTextWriter fileWriter = new XmlTextWriter( filename, Encoding.UTF8 ); e.WriteTo( fileWriter ); fileWriter.Flush(); fileWriter.Close(); }
public void SetMimeTypeAfterId () { XmlElement el = new XmlDocument ().CreateElement ("foo"); DataObject d = new DataObject ("id:1", null, null, el); d.MimeType = "text/html"; Assert.AreEqual ("id:1", d.Id); }
public void EnvelopedObject () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<envelope><Object xmlns:dsig='http://www.w3.org/2000/09/xmldsig#' xmlns='http://www.w3.org/2000/09/xmldsig#'>test</Object></envelope>"); DataObject obj = new DataObject (); obj.LoadXml (doc.DocumentElement.FirstChild as XmlElement); obj.Id = "hoge"; obj.MimeType = "application/octet-stream"; obj.Encoding = "euc-kr"; XmlElement el1 = obj.GetXml (); Assert.AreEqual ("<Object Id=\"hoge\" MimeType=\"application/octet-stream\" Encoding=\"euc-kr\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\">test</Object>", el1.OuterXml); /* looks curious? but the element does not look to be appended to the document. Just commented out since it is not fixed. Assert.AreEqual (String.Empty, el1.OwnerDocument.OuterXml); */ }
// The same as MSDNSample(), but adding a few attributes public SignedXml MSDNSampleMixedCaseAttributes () { // Create example data to sign. XmlDocument document = new XmlDocument (); XmlNode node = document.CreateNode (XmlNodeType.Element, "", "MyElement", "samples"); node.InnerText = "This is some text"; XmlAttribute a1 = document.CreateAttribute ("Aa"); XmlAttribute a2 = document.CreateAttribute ("Bb"); XmlAttribute a3 = document.CreateAttribute ("aa"); XmlAttribute a4 = document.CreateAttribute ("bb"); a1.Value = "one"; a2.Value = "two"; a3.Value = "three"; a4.Value = "four"; node.Attributes.Append (a1); node.Attributes.Append (a2); node.Attributes.Append (a3); node.Attributes.Append (a4); document.AppendChild (node); // Create the SignedXml message. SignedXml signedXml = new SignedXml (); // Create a data object to hold the data to sign. DataObject dataObject = new DataObject (); dataObject.Data = document.ChildNodes; dataObject.Id = "MyObjectId"; // Add the data object to the signature. signedXml.AddObject (dataObject); // Create a reference to be able to package everything into the // message. Reference reference = new Reference (); reference.Uri = "#MyObjectId"; // Add it to the message. signedXml.AddReference (reference); return signedXml; }
public void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } XmlElement element = value; if (!element.LocalName.Equals("Signature")) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature"); } this.m_id = System.Security.Cryptography.Xml.Utils.GetAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#"); XmlNamespaceManager nsmgr = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsmgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#"); XmlElement element2 = element.SelectSingleNode("ds:SignedInfo", nsmgr) as XmlElement; if (element2 == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo"); } this.SignedInfo = new System.Security.Cryptography.Xml.SignedInfo(); this.SignedInfo.LoadXml(element2); XmlElement element3 = element.SelectSingleNode("ds:SignatureValue", nsmgr) as XmlElement; if (element3 == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo/SignatureValue"); } this.m_signatureValue = Convert.FromBase64String(System.Security.Cryptography.Xml.Utils.DiscardWhiteSpaces(element3.InnerText)); this.m_signatureValueId = System.Security.Cryptography.Xml.Utils.GetAttribute(element3, "Id", "http://www.w3.org/2000/09/xmldsig#"); XmlNodeList list = element.SelectNodes("ds:KeyInfo", nsmgr); this.m_keyInfo = new System.Security.Cryptography.Xml.KeyInfo(); if (list != null) { foreach (XmlNode node in list) { XmlElement element4 = node as XmlElement; if (element4 != null) { this.m_keyInfo.LoadXml(element4); } } } XmlNodeList list2 = element.SelectNodes("ds:Object", nsmgr); this.m_embeddedObjects.Clear(); if (list2 != null) { foreach (XmlNode node2 in list2) { XmlElement element5 = node2 as XmlElement; if (element5 != null) { DataObject obj2 = new DataObject(); obj2.LoadXml(element5); this.m_embeddedObjects.Add(obj2); } } } XmlNodeList list3 = element.SelectNodes("//*[@Id]", nsmgr); if (list3 != null) { foreach (XmlNode node3 in list3) { this.m_referencedItems.Add(node3); } } }
public void AddObject(DataObject dataObject) { this.m_embeddedObjects.Add(dataObject); }
public static string SignXMLX509Data(string strXML) { string strResult = ""; try { SignedXml signedXml = new SignedXml(); // Get the signature key. For this demo, we look for keys associated with a certificate in the "MY" store RSACryptoServiceProvider rsa = null; X509Certificate x509Cert = null; GetSignatureKey(out rsa, out x509Cert); if (rsa == null) return ""; signedXml.SigningKey = rsa; Reference reference = new Reference(); reference.Uri = "#object-1"; reference.Type = "http://www.w3.org/2000/09/xmldsig#Object"; // Add an object System.Security.Cryptography.Xml.DataObject obj = new System.Security.Cryptography.Xml.DataObject(); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(strXML); obj.Data = doc.ChildNodes; obj.Id = "object-1"; signedXml.AddObject(obj); signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); // Include the certificate raw data with the signed file keyInfo.AddClause(new KeyInfoX509Data(x509Cert)); signedXml.KeyInfo = keyInfo; // compute the signature signedXml.ComputeSignature(); strResult = signedXml.GetXml().OuterXml; } catch (Exception exc) { MessageBox.Show(exc.ToString(), Messages.ExceptionTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop); return strResult; } return strResult; }
static DCinemaSecurityMessageType SignETM(DCinemaSecurityMessageType extraTheatreMessage, X509Certificate2 x509Certificate2) { SignedXml signedXml = null; try { signedXml = new SignedXml(); signedXml.SigningKey = x509Certificate2.PrivateKey; //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/ 2001/04/xmldsig-more#rsasha256"; //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; StringWriter stringWriter = new StringWriter(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(DCinemaSecurityMessageType)); xmlSerializer.Serialize(stringWriter, extraTheatreMessage); string serializedXML = stringWriter.ToString(); #region Build the AuthenticatedPublic DataObject & Reference string xmlAuthenticatedPublic = GetCleanElement(serializedXML, "AuthenticatedPublic"); XmlDocument docAuthenticatedPublic = new XmlDocument(); docAuthenticatedPublic.LoadXml(xmlAuthenticatedPublic.ToString()); //XmlAttribute attrAuthenticatedPublic = docAuthenticatedPublic.CreateAttribute("xmlns"); //attrAuthenticatedPublic.Value = "http://www.smpte-ra.org/schemas/430-3/2006/ETM"; //docAuthenticatedPublic.DocumentElement.Attributes.Append(attrAuthenticatedPublic); DataObject dataObjectAuthenticatedPublic = new DataObject("AuthenticatedPublic", "", "", docAuthenticatedPublic.DocumentElement); //DataObject dataObjectAuthenticatedPublic = new DataObject(); dataObjectAuthenticatedPublic.Data = docAuthenticatedPublic.ChildNodes; dataObjectAuthenticatedPublic.Id = "AuthenticatedPublic"; signedXml.AddObject(dataObjectAuthenticatedPublic); Reference referenceAuthenticatedPublic = new Reference(); referenceAuthenticatedPublic.Uri = "#AuthenticatedPublic"; referenceAuthenticatedPublic.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; signedXml.AddReference(referenceAuthenticatedPublic); #endregion #region Build the AuthenticatedPublic DataObject & Reference string xmlAuthenticatedPrivate = GetCleanElement(serializedXML, "AuthenticatedPrivate"); XmlDocument docAuthenticatedPrivate = new XmlDocument(); docAuthenticatedPrivate.LoadXml(xmlAuthenticatedPrivate.ToString()); //XmlAttribute attrAuthenticatedPrivate = docAuthenticatedPrivate.CreateAttribute("xmlns"); //attrAuthenticatedPrivate.Value = "http://www.smpte-ra.org/schemas/430-3/2006/FLM"; //docAuthenticatedPrivate.DocumentElement.Attributes.Append(attrAuthenticatedPrivate); DataObject dataObjectAuthenticatedPrivate = new DataObject("AuthenticatedPrivate", "", "", docAuthenticatedPrivate.DocumentElement); //DataObject dataObjectAuthenticatedPrivate = new DataObject("AuthenticatedPrivate", "", "", docAuthenticatedPrivate.DocumentElement); //dataObjectAuthenticatedPrivate.Data = docAuthenticatedPrivate.ChildNodes; //dataObjectAuthenticatedPrivate.Id = "AuthenticatedPrivate"; signedXml.AddObject(dataObjectAuthenticatedPrivate); Reference referenceAuthenticatedPrivate = new Reference(); referenceAuthenticatedPrivate.Uri = "#AuthenticatedPrivate"; referenceAuthenticatedPrivate.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; // Add the reference to the message. signedXml.AddReference(referenceAuthenticatedPrivate); #endregion // Add a KeyInfo. KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(x509Certificate2, X509IncludeOption.WholeChain)); signedXml.KeyInfo = keyInfo; // Compute the signature. signedXml.ComputeSignature(); XmlElement singedElement = signedXml.GetXml(); XmlSerializer signedSerializer = new XmlSerializer(singedElement.GetType()); StreamWriter signedWriter = new StreamWriter(@"\SOURCE_SMPTE\Output\signedSerializer.Test.xml"); signedSerializer.Serialize(signedWriter, singedElement); signedWriter.Close(); } catch (CryptographicException e) { Console.WriteLine(e.Message); } extraTheatreMessage.Signature = signedXml.Signature.GetXml(); return extraTheatreMessage; }
public void GetXmlKeepDocument () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<Object xmlns='http://www.w3.org/2000/09/xmldsig#'>test</Object>"); DataObject obj = new DataObject (); XmlElement el1 = obj.GetXml (); obj.LoadXml (doc.DocumentElement); // obj.Id = "hogehoge"; XmlElement el2 = obj.GetXml (); Assert.AreEqual (doc, el2.OwnerDocument, "Document is kept unless setting properties"); }
/** * Sign the payloadBody as-is. Note that this is going to be encrypted anyway * so we avoid any incompatibilities due to canonicalisation, and we don't * care if the payloadBody is text, compressed and so on. Re-writes payloadBody * with a serialised XML Digital Signature "Signature" element containing an * enveloping signature, or throws an exception to signal failure. * * @param pk Private key * @param cert certificate associated with private key * @throws Exception */ private void signPayload(AsymmetricAlgorithm pk, X509Certificate2 cert) { if ((pk == null) || (cert == null)) { throw new Exception("Null signing material"); } if (!checkCertificateDateRange(cert)) { throw new Exception("Cannot use certificate " + cert.SubjectName + " as it is out of date"); } Reference reference = null; DataObject dataObject = null; XmlDocument doc = new XmlDocument(); String objectRef = "uuid" + Guid.NewGuid().ToString().ToLower(); reference = new Reference("#" + objectRef); if (compressed || base64 || !mimeType.Contains("xml")) { // Reference to the encoded binary content, using the (default) SHA1 DigestMethod // dataObject = new DataObject(); XmlText t = doc.CreateTextNode(payloadBody); // This element is just created as a workaround to contain the text, because .Net // won't let us include an XmlTextNode directly like the JDK will. We actually // grab the text node back out again in an XmlNodeList, which seems to keep the // .Net signer happy. // XmlElement element = doc.CreateElement("X"); element.AppendChild(t); XmlNodeList nl = element.ChildNodes; dataObject.Data = nl; } else { // Reference to the XML payload, using the (default) SHA1 DigestMethod and // exclusive canonicalisation. // reference.AddTransform(new XmlDsigExcC14NTransform()); doc.LoadXml(payloadBody); dataObject.Data = doc.ChildNodes; } dataObject.Encoding = ""; dataObject.Id = objectRef; dataObject.MimeType = ""; SignedXml signedXml = new SignedXml(); signedXml.AddObject(dataObject); signedXml.AddReference(reference); signedXml.SigningKey = pk; KeyInfo ki = new KeyInfo(); ki.AddClause(new KeyInfoX509Data(cert)); signedXml.KeyInfo = ki; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigC14NWithCommentsTransformUrl; signedXml.ComputeSignature(); payloadBody = signedXml.Signature.GetXml().OuterXml; }
public void PropertySetMakesDocumentDifferent () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<Object xmlns='http://www.w3.org/2000/09/xmldsig#'>test</Object>"); DataObject obj = new DataObject (); XmlElement el1 = obj.GetXml (); obj.LoadXml (doc.DocumentElement); obj.Id = "hogehoge"; XmlElement el2 = obj.GetXml (); Assert.IsTrue (doc != el2.OwnerDocument, "Document is not kept when properties are set"); }
/// <summary> /// Signiert ein Xml-Document. /// </summary> /// <param name="xDoc">Das Dokument welches die Daten enthält die signiert werden sollen.</param> /// <param name="privateKey">Der private Schlüssel.</param> /// <returns>Gibt ein Xml Element mit den Signierten daten zurück.</returns> public static XmlElement SignXmlDocument(XmlDocument xDoc, string privateKey) { var signedXml = new SignedXml(); System.Security.Cryptography.RSA pvk = System.Security.Cryptography.RSA.Create(); pvk.FromXmlString(privateKey); signedXml.SigningKey = pvk; var dataObject = new DataObject(); dataObject.Id = "content"; dataObject.Data = xDoc.ChildNodes; signedXml.AddObject(dataObject); var reference = new Reference(); reference.Uri = "#content"; signedXml.AddReference(reference); var keyinfo = new KeyInfo(); keyinfo.AddClause(new RSAKeyValue(pvk)); signedXml.KeyInfo = keyinfo; signedXml.ComputeSignature(); return signedXml.GetXml(); }
public void SetDataAfterId () { DataObject d = new DataObject (); XmlElement el = new XmlDocument ().CreateElement ("foo"); d.Id = "id:1"; d.Data = el.SelectNodes ("."); Assert.AreEqual ("id:1", d.Id); }
public void LoadXml(XmlElement value) { // Make sure we don't get passed null if (value == null) throw new ArgumentNullException("value"); // Signature XmlElement signatureElement = value; if (!signatureElement.LocalName.Equals("Signature")) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature"); // Id attribute -- optional m_id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); // SignedInfo XmlElement signedInfoElement = signatureElement.SelectSingleNode("ds:SignedInfo", nsm) as XmlElement; if (signedInfoElement == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"),"SignedInfo"); this.SignedInfo = new SignedInfo(); this.SignedInfo.LoadXml(signedInfoElement); // SignatureValue XmlElement signatureValueElement = signatureElement.SelectSingleNode("ds:SignatureValue", nsm) as XmlElement; if (signatureValueElement == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"),"SignedInfo/SignatureValue"); m_signatureValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText)); m_signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl); XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm); m_keyInfo = new KeyInfo(); if (keyInfoNodes != null) { foreach(XmlNode node in keyInfoNodes) { XmlElement keyInfoElement = node as XmlElement; if (keyInfoElement != null) m_keyInfo.LoadXml(keyInfoElement); } } XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm); m_embeddedObjects.Clear(); if (objectNodes != null) { foreach(XmlNode node in objectNodes) { XmlElement objectElement = node as XmlElement; if (objectElement != null) { DataObject dataObj = new DataObject(); dataObj.LoadXml(objectElement); m_embeddedObjects.Add(dataObj); } } } // Select all elements that have Id attributes XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm); if (nodeList != null) { foreach (XmlNode node in nodeList) { m_referencedItems.Add(node); } } }
public void LoadXml(XmlElement value) { // Make sure we don't get passed null if (value == null) { throw new ArgumentNullException(nameof(value)); } // Signature XmlElement signatureElement = value; if (!signatureElement.LocalName.Equals("Signature")) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature"); } // Id attribute -- optional _id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl); if (!Utils.VerifyAttributes(signatureElement, "Id")) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature"); } XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); int expectedChildNodes = 0; // SignedInfo XmlNodeList signedInfoNodes = signatureElement.SelectNodes("ds:SignedInfo", nsm); if (signedInfoNodes == null || signedInfoNodes.Count == 0 || signedInfoNodes.Count > 1) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo"); } XmlElement signedInfoElement = signedInfoNodes[0] as XmlElement; expectedChildNodes += signedInfoNodes.Count; SignedInfo = new SignedInfo(); SignedInfo.LoadXml(signedInfoElement); // SignatureValue XmlNodeList signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm); if (signatureValueNodes == null || signatureValueNodes.Count == 0 || signatureValueNodes.Count > 1) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue"); } XmlElement signatureValueElement = signatureValueNodes[0] as XmlElement; expectedChildNodes += signatureValueNodes.Count; _signatureValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText)); _signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl); if (!Utils.VerifyAttributes(signatureValueElement, "Id")) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue"); } // KeyInfo - optional single element XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm); _keyInfo = new KeyInfo(); if (keyInfoNodes != null) { if (keyInfoNodes.Count > 1) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "KeyInfo"); } foreach (XmlNode node in keyInfoNodes) { XmlElement keyInfoElement = node as XmlElement; if (keyInfoElement != null) { _keyInfo.LoadXml(keyInfoElement); } } expectedChildNodes += keyInfoNodes.Count; } // Object - zero or more elements allowed XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm); _embeddedObjects.Clear(); if (objectNodes != null) { foreach (XmlNode node in objectNodes) { XmlElement objectElement = node as XmlElement; if (objectElement != null) { DataObject dataObj = new DataObject(); dataObj.LoadXml(objectElement); _embeddedObjects.Add(dataObj); } } expectedChildNodes += objectNodes.Count; } // Select all elements that have Id attributes XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm); if (nodeList != null) { foreach (XmlNode node in nodeList) { _referencedItems.Add(node); } } // Verify that there aren't any extra nodes that aren't allowed if (signatureElement.SelectNodes("*").Count != expectedChildNodes) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature"); } }
public void AddObject(DataObject dataObject) { m_signature.AddObject(dataObject); }
public void InvalidDataObject1 () { DataObject obj1 = new DataObject (); obj1.Data = null; }
private static DataObject CreateOfficeObject(string signatureID, string manifestHashAlgorithm) { var document = new XmlDocument(); document.LoadXml(String.Format(Properties.Resources.OfficeObject, signatureID, manifestHashAlgorithm)); var officeObject = new DataObject(); // do not change the order of the following two lines officeObject.LoadXml(document.DocumentElement); // resets ID officeObject.Id = OfficeObjectID; // required ID, do not change return officeObject; }
/// <summary> /// Add a XAdES object to the signature /// </summary> /// <param name="xadesObject">XAdES object to add to signature</param> public void AddXadesObject(XadesObject xadesObject) { Reference reference; DataObject dataObject; XmlElement bufferXmlElement; if (this.SignatureStandard != KnownSignatureStandard.Xades) { dataObject = new DataObject(); dataObject.Id = xadesObject.Id; dataObject.Data = xadesObject.GetXml().ChildNodes; this.AddObject(dataObject); //Add the XAdES object reference = new Reference(); signedPropertiesIdBuffer = xadesObject.QualifyingProperties.SignedProperties.Id; reference.Uri = "#" + signedPropertiesIdBuffer; reference.Type = SignedPropertiesType; this.AddReference(reference); //Add the XAdES object reference this.cachedXadesObjectDocument = new XmlDocument(); bufferXmlElement = xadesObject.GetXml(); // Add "ds" namespace prefix to all XmlDsig nodes in the XAdES object SetPrefix("ds", bufferXmlElement); this.cachedXadesObjectDocument.PreserveWhitespace = true; this.cachedXadesObjectDocument.LoadXml(bufferXmlElement.OuterXml); //Cache to XAdES object for later use this.signatureStandard = KnownSignatureStandard.Xades; } else { throw new CryptographicException("Can't add XAdES object, the signature already contains a XAdES object"); } }
// sample from MSDN (url) public SignedXml MSDNSample () { // Create example data to sign. XmlDocument document = new XmlDocument (); XmlNode node = document.CreateNode (XmlNodeType.Element, "", "MyElement", "samples"); node.InnerText = "This is some text"; document.AppendChild (node); // Create the SignedXml message. SignedXml signedXml = new SignedXml (); // Create a data object to hold the data to sign. DataObject dataObject = new DataObject (); dataObject.Data = document.ChildNodes; dataObject.Id = "MyObjectId"; // Add the data object to the signature. signedXml.AddObject (dataObject); // Create a reference to be able to package everything into the // message. Reference reference = new Reference (); reference.Uri = "#MyObjectId"; // Add it to the message. signedXml.AddReference (reference); return signedXml; }
private void addReferenceButton_Click(object sender, System.EventArgs e) { XmlDsigEnvelopedSignatureTransform xmlDsigEnvelopedSignatureTransform; Reference reference; reference = new Reference(); if (this.envelopedSignatureRadioButton.Checked) { if (this.newSignatureCheckBox.Checked) { this.envelopedSignatureXmlDocument = new XmlDocument(); this.documentDataObjectCounter = 1; } this.envelopedSignatureXmlDocument.PreserveWhitespace = true; this.envelopedSignatureXmlDocument.Load(this.envelopingDocumentTextBox.Text); this.xadesSignedXml = new XadesSignedXml(this.envelopedSignatureXmlDocument); reference.Uri = ""; XmlDsigC14NTransform xmlDsigC14NTransform = new XmlDsigC14NTransform(); reference.AddTransform(xmlDsigC14NTransform); xmlDsigEnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(xmlDsigEnvelopedSignatureTransform); } else { if (this.newSignatureCheckBox.Checked) { this.xadesSignedXml = new XadesSignedXml(); this.documentDataObjectCounter = 1; } if (this.includedXmlRadioButton.Checked) { reference.Uri = "#" + this.objectIdPrefixTextBox.Text + this.documentDataObjectCounter.ToString(); reference.Type = SignedXml.XmlDsigNamespaceUrl + "Object"; //Add an object System.Security.Cryptography.Xml.DataObject dataObject = new System.Security.Cryptography.Xml.DataObject(); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; xmlDocument.LoadXml(this.includedXmltextBox.Text); dataObject.Data = xmlDocument.ChildNodes; dataObject.Id = this.objectIdPrefixTextBox.Text + this.documentDataObjectCounter.ToString(); this.xadesSignedXml.AddObject(dataObject); } else { reference.Uri = this.externalDocumentUrlTextBox.Text; if (reference.Uri.EndsWith(".xml") || reference.Uri.EndsWith(".XML")) { reference.AddTransform(new XmlDsigC14NTransform()); } } } this.xadesSignedXml.AddReference(reference); this.documentDataObjectCounter++; this.nextObjectIdSuffixLabel.Text = this.documentDataObjectCounter.ToString(); }
string SignWithHMACSHA1 (string input, byte [] key, Transform transform) { XmlDocument doc = new XmlDocument (); doc.LoadXml (input); SignedXml sxml = new SignedXml (doc); HMACSHA1 keyhash = new HMACSHA1 (key); DataObject d = new DataObject (); //d.Data = doc.SelectNodes ("//*[local-name()='Body']/*"); d.Data = doc.SelectNodes ("//*[local-name()='Action']"); d.Id = "_1"; sxml.AddObject (d); Reference r = new Reference ("#_1"); r.AddTransform (transform); r.DigestMethod = SignedXml.XmlDsigSHA1Url; sxml.SignedInfo.AddReference (r); sxml.ComputeSignature (keyhash); StringWriter sw = new StringWriter (); XmlWriter w = new XmlTextWriter (sw); sxml.GetXml ().WriteTo (w); w.Close (); return sw.ToString (); }
/////////////////////////////////////////////////////////////////////// /// /// <summary> /// Carry out the Sign command. /// </summary> /// static void DoSignCommand(string title, X509Certificate2 certificate) { Console.WriteLine(); Console.WriteLine("Signing Xml file \"" + fileNames[0] + "\"..."); Console.WriteLine(); // display more details for verbose operation. if (verbose) { DisplayDetail(null, certificate, detached); } SignedXml signedXml = new SignedXml(); ICspAsymmetricAlgorithm csp = (ICspAsymmetricAlgorithm) certificate.PrivateKey; if (csp.CspKeyContainerInfo.RandomlyGenerated) throw new InternalException("Internal error: This certificate does not have a corresponding private key."); signedXml.SigningKey = (AsymmetricAlgorithm) csp; Console.WriteLine(signedXml.SigningKey.ToXmlString(false)); if (detached) { Reference reference = new Reference(); reference.Uri = "file://" + Path.GetFullPath((string) fileNames[0]); signedXml.AddReference(reference); } else { Reference reference = new Reference(); reference.Uri = "#object-1"; // Add an object XmlDocument dataObject = new XmlDocument(); dataObject.PreserveWhitespace = true; XmlElement dataElement = (XmlElement) dataObject.CreateElement("DataObject", SignedXml.XmlDsigNamespaceUrl); dataElement.AppendChild(dataObject.CreateTextNode(new UTF8Encoding(false).GetString(ReadFile((string) fileNames[0])))); dataObject.AppendChild(dataElement); DataObject obj = new DataObject(); obj.Data = dataObject.ChildNodes; obj.Id = "object-1"; signedXml.AddObject(obj); signedXml.AddReference(reference); } signedXml.KeyInfo = new KeyInfo(); if (includeOptions.Count == 0) { signedXml.KeyInfo.AddClause(new KeyInfoX509Data(certificate, X509IncludeOption.ExcludeRoot)); } else { KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(); foreach (IncludeOptions includeOption in includeOptions) { switch (includeOption) { case IncludeOptions.ExcludeRoot: case IncludeOptions.EndCertOnly: case IncludeOptions.WholeChain: keyInfoX509Data = new KeyInfoX509Data(certificate, (X509IncludeOption) includeOption); break; case IncludeOptions.SubjectName: keyInfoX509Data.AddSubjectName(certificate.SubjectName.Name); break; case IncludeOptions.SKI: X509ExtensionCollection extensions = certificate.Extensions; foreach (X509Extension extension in extensions) { if (extension.Oid.Value == "2.5.29.14") { // OID for SKI extension X509SubjectKeyIdentifierExtension ski = extension as X509SubjectKeyIdentifierExtension; if (ski != null) { keyInfoX509Data.AddSubjectKeyId(ski.SubjectKeyIdentifier); break; } } } break; case IncludeOptions.IssuerSerial: keyInfoX509Data.AddIssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber); break; } signedXml.KeyInfo.AddClause(keyInfoX509Data); } } // compute the signature signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); // write it out XmlTextWriter xmltw = new XmlTextWriter((string) fileNames[1], new UTF8Encoding(false)); xmlDigitalSignature.WriteTo(xmltw); xmltw.Close(); Console.WriteLine(); Console.WriteLine("Signature written to file \"" + fileNames[1] + "\"."); Console.WriteLine(); return; }