Ejemplo n.º 1
40
        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);
        }
Ejemplo n.º 2
0
        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);
            }
        }
Ejemplo n.º 3
0
		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 ();
		}
Ejemplo n.º 4
0
		public void Add_Null () 
		{
			SignedXml sx = new SignedXml ();
			// no ArgumentNull exceptions for those
			sx.AddObject (null);
			sx.AddReference (null);
		}
Ejemplo n.º 5
0
		// [ExpectedException (typeof (ArgumentNullException))]
		public void AddObject_Null () 
		{
			SignedXml sx = new SignedXml ();
			// still no ArgumentNullExceptions for this one
			sx.AddObject (null);
		}
Ejemplo n.º 6
0
		// 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;
		}
Ejemplo n.º 7
0
		// 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;
		}
Ejemplo n.º 8
0
        ///////////////////////////////////////////////////////////////////////
        ///
        /// <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;
        }
Ejemplo n.º 9
0
        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;
        }
Ejemplo n.º 10
0
        /// <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();
        }
        /**
         * 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;
        }
Ejemplo n.º 12
0
        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;
        }
        private void OpprettReferanser(SignedXml signaturnode, IEnumerable<IAsiceAttachable> referanser)
        {
            foreach (var item in referanser)
            {
                signaturnode.AddReference(Sha256Referanse(item));
            }

            signaturnode.AddObject(
                new QualifyingPropertiesObject(
                    _sertifikat, "#Signature", referanser.ToArray(), _xml.DocumentElement)
                );

            signaturnode.AddReference(SignedPropertiesReferanse());
        }
Ejemplo n.º 14
0
		/// <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();
		}
Ejemplo n.º 15
0
        static DCinemaSecurityMessageType SignETM(DCinemaSecurityMessageType extraTheatreMessage, X509Certificate2 x509Certificate2)
        {
            SignedXml signedXml = null;
            try
            {
                #region build the signature object
                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";
                #endregion

                #region build a DCinemaSecurityMessage string to pull Data Objects
                StringWriter stringWriter = new StringWriter();
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(DCinemaSecurityMessageType));
                xmlSerializer.Serialize(stringWriter, extraTheatreMessage);
                string serializedXML = stringWriter.ToString();
                #endregion

                #region Build the AuthenticatedPublic DataObject & Reference

                string xmlAuthenticatedPublic = GetCleanElement(serializedXML, "AuthenticatedPublic");
                XmlDocument docAuthenticatedPublic = new XmlDocument();
                docAuthenticatedPublic.LoadXml(xmlAuthenticatedPublic.ToString());

                DataObject dataObjectAuthenticatedPublic = new DataObject("AuthenticatedPublic", "", "", docAuthenticatedPublic.DocumentElement);
                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());

                DataObject dataObjectAuthenticatedPrivate = new DataObject("AuthenticatedPrivate", "", "", docAuthenticatedPrivate.DocumentElement);

                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

                #region Add KeyInfo.
                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(x509Certificate2, X509IncludeOption.WholeChain));
                signedXml.KeyInfo = keyInfo;
                #endregion

                // Compute the signature.
                signedXml.ComputeSignature();
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
            }

            //add the signature to the DCinemaSecurityMessage
            extraTheatreMessage.Signature = signedXml.Signature.GetXml();

            return extraTheatreMessage;
        }