コード例 #1
3
ファイル: Program.cs プロジェクト: FraGoTe/xml-crypto
    // Sign an XML file and save the signature in a new file. This method does not  
    // save the public key within the XML file.  This file cannot be verified unless  
    // the verifying code has the key with which it was signed.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Load the passed XML file using its name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document. 
        signedXml.SigningKey = Key;

        // Create a reference to be signed.
        Reference reference = new Reference();
        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
        reference.AddTransform(env);

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
        doc.WriteTo(xmltw);
        xmltw.Close();
    }
コード例 #2
2
ファイル: cra.cs プロジェクト: dimakura/cra.ge
	static void Main(string[] args) {
		if (args.Length != 4) {
			Console.WriteLine("Usage: cra.exe cert-file cert-password input-path output-path");
			return;
		}

		String certFile = args[0];
		String password = args[1];
		String input    = args[2];
		String output   = args[3];

		X509Certificate2 cert = new X509Certificate2(certFile, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

		XmlDocument xmlDoc = new XmlDocument();
		xmlDoc.Load(input);

		var XmlToSign = new XmlDocument();
  	XmlToSign.LoadXml(xmlDoc.DocumentElement["Body"].OuterXml);

		SignedXml signedXml = new SignedXml(XmlToSign);
		signedXml.SigningKey = cert.PrivateKey;

		Reference reference = new Reference();
		reference.Uri = "";

    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
    reference.AddTransform(env);

		signedXml.AddReference(reference);
		signedXml.ComputeSignature();
		XmlElement xmlDigitalSignature = signedXml.GetXml();
		xmlDoc.DocumentElement["Body"].AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
		xmlDoc.Save(output);
	}
コード例 #3
0
        public static string firmarDocumentoSemilla(string documento, X509Certificate2 certificado)
        {
            ////
            //// Cree un nuevo documento xml y defina sus caracteristicas
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = false;
            doc.LoadXml(documento);
            SignedXml signedXml = new SignedXml(doc);

            signedXml.SigningKey = certificado.PrivateKey;
            Signature XMLSignature = signedXml.Signature;
            Reference reference    = new Reference("");
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            XMLSignature.SignedInfo.AddReference(reference);
            KeyInfo keyInfo = new KeyInfo();

            keyInfo.AddClause(new RSAKeyValue((RSA)certificado.PrivateKey));
            keyInfo.AddClause(new KeyInfoX509Data(certificado));
            XMLSignature.KeyInfo = keyInfo;
            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));


            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            return(doc.InnerXml);
        }
コード例 #4
0
ファイル: QcProtect.cs プロジェクト: cug-weipeng/ExDevice-1
        public void Makelicense(string pritivefile, string keyfile, string licensefile)
        {
            string pubKey = ReadPublicKey(pritivefile);
            RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

            Key.FromXmlString(pubKey);
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(keyfile);
            var pub = xmlDoc.CreateElement("PublicKey");

            pub.InnerXml = Key.ToXmlString(false);
            xmlDoc.SelectSingleNode("IGCESLicense").AppendChild(pub);
            //xmlDoc.Save(licensefile);
            SignedXml signedXml = new SignedXml(xmlDoc);

            signedXml.SigningKey = Key;
            Reference reference = new Reference();

            reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            signedXml.AddReference(reference);
            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
            xmlDoc.Save(licensefile);
        }
コード例 #5
0
        public XmlDocument FirmarXml(X509Certificate2 x509Certificate2, XmlDocument xmlDocument, string strReference)
        {
            xmlDocument.PreserveWhitespace = true;
            SignedXml signedXml = new SignedXml(xmlDocument);

            signedXml.SigningKey = x509Certificate2.PrivateKey;
            Signature XMLSignature = signedXml.Signature;

            Reference reference = new Reference(strReference);

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            XMLSignature.SignedInfo.AddReference(reference);

            KeyInfo keyInfo = new KeyInfo();

            keyInfo.AddClause(new RSAKeyValue((RSA)x509Certificate2.PrivateKey));
            keyInfo.AddClause(new KeyInfoX509Data(x509Certificate2));

            XMLSignature.KeyInfo = keyInfo;

            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(xmlDigitalSignature, true));

            return(xmlDocument);
        }
コード例 #6
0
        static void SignXmlFile(string outputName)
        {
            CspParameters cspParams = new CspParameters();

            cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(outputName);
            SignedXml signedXml = new SignedXml(xmlDoc);

            signedXml.SigningKey = rsaKey;

            // Create a Reference object that describes what to sign. To sign the entire document, set the Uri property to "".
            Reference reference = new Reference();

            reference.Uri = "";

            // Add an XmlDsigEnvelopedSignatureTransform object to the Reference object. A transformation allows the verifier to represent the XML data in the identical manner that the signer used.
            // XML data can be represented in different ways, so this step is vital to verification.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
            xmlDoc.Save(outputName);
        }
コード例 #7
0
        /// <summary>
        /// Construye el documento enveloped
        /// </summary>
        private void CreateEnvelopedDocument()
        {
            Reference reference = new Reference();

            _xadesSignedXml = new XadesSignedXml(_document);

            reference.Id  = "Reference-" + Guid.NewGuid().ToString();
            reference.Uri = "";

            for (int i = 0; i < _document.DocumentElement.Attributes.Count; i++)
            {
                if (_document.DocumentElement.Attributes[i].Name.Equals("id", StringComparison.InvariantCultureIgnoreCase))
                {
                    reference.Uri = "#" + _document.DocumentElement.Attributes[i].Value;
                    break;
                }
            }

            XmlDsigEnvelopedSignatureTransform xmlDsigEnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(xmlDsigEnvelopedSignatureTransform);

            _objectReference = reference.Id;

            _xadesSignedXml.AddReference(reference);
        }
コード例 #8
0
ファイル: SignatureTest.cs プロジェクト: Tom-FP/OIOSAML.Net
        /// <summary>
        /// Signs the document given as an argument.
        /// </summary>
        private static void SignDocument(XmlDocument doc)
        {
            SignedXml signedXml = new SignedXml(doc);

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            // TODO Dynamically dig out the correct ID attribute from the XmlDocument.
            Reference reference = new Reference("#_b8977dc86cda41493fba68b32ae9291d");
            // Assert.That(reference.Uri == string.Empty);

            XmlDsigEnvelopedSignatureTransform envelope = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(envelope);

            // NOTE: C14n may require the following list of namespace prefixes. Seems to work without it, though.
            //List<string> prefixes = new List<string>();
            //prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("http://www.w3.org/2000/09/xmldsig#"));
            //prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("http://www.w3.org/2001/XMLSchema-instance"));
            //prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("http://www.w3.org/2001/XMLSchema"));
            //prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("urn:oasis:names:tc:SAML:2.0:assertion"));

            //XmlDsigExcC14NTransform C14NTransformer = new XmlDsigExcC14NTransform(string.Join(" ", prefixes.ToArray()).Trim());
            XmlDsigExcC14NTransform C14NTransformer = new XmlDsigExcC14NTransform();

            reference.AddTransform(C14NTransformer);

            signedXml.AddReference(reference);

            // Add the key to the signature, so the assertion can be verified by itself.
            signedXml.KeyInfo = new KeyInfo();

            // Use RSA key for signing.
            //{
            //    CspParameters parameters = new CspParameters();
            //    parameters.KeyContainerName = "XML_DSIG_RSA_KEY";
            //    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(parameters);
            //    signedXml.SigningKey = rsaKey;
            //    signedXml.KeyInfo.AddClause(new RSAKeyValue(rsaKey));
            //}

            // Use X509 Certificate for signing.
            {
                X509Certificate2 cert = new X509Certificate2(@"Saml20\Certificates\sts_dev_certificate.pfx", "test1234");
                Assert.That(cert.HasPrivateKey);
                signedXml.SigningKey = cert.GetRSAPrivateKey();
                signedXml.KeyInfo.AddClause(new KeyInfoX509Data(cert, X509IncludeOption.EndCertOnly));
            }

            // Information on the these and other "key info clause" types can be found at:
            // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref18/html/T_System_Security_Cryptography_Xml_KeyInfoClause_DerivedTypes.htm

            // Do it!
            signedXml.ComputeSignature();

            XmlNodeList nodes = doc.DocumentElement.GetElementsByTagName("Issuer", Saml20Constants.ASSERTION);

            Assert.That(nodes.Count == 1);
            XmlNode node = nodes[0];

            doc.DocumentElement.InsertAfter(doc.ImportNode(signedXml.GetXml(), true), node);
        }
コード例 #9
0
ファイル: members.cs プロジェクト: zhimaqiao51/docs
    // Resolve the specified base and relative Uri's .
    private static Uri ResolveUris(Uri baseUri, string relativeUri)
    {
        //<Snippet7>
        XmlUrlResolver xmlResolver = new XmlUrlResolver();

        xmlResolver.Credentials =
            System.Net.CredentialCache.DefaultCredentials;

        XmlDsigEnvelopedSignatureTransform xmlTransform =
            new XmlDsigEnvelopedSignatureTransform();

        xmlTransform.Resolver = xmlResolver;
        //</Snippet7>

        Uri absoluteUri = xmlResolver.ResolveUri(baseUri, relativeUri);

        if (absoluteUri != null)
        {
            Console.WriteLine(
                "\nResolved the base Uri and relative Uri to the following:");
            Console.WriteLine(absoluteUri.ToString());
        }
        else
        {
            Console.WriteLine(
                "Unable to resolve the base Uri and relative Uri");
        }
        return(absoluteUri);
    }
コード例 #10
0
ファイル: Program.cs プロジェクト: MalykhAlexandr/ApplyN
        // Sign an XML file.
        // This document cannot be verified unless the verifying
        // code has the key with which it was signed.
        public static void SignXml(XmlDocument xmlDoc, RSA Key)
        {
            // Check arguments.
            if (xmlDoc == null)
            {
                throw new ArgumentException("xmlDoc");
            }
            if (Key == null)
            {
                throw new ArgumentException("Key");
            }
            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(xmlDoc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = Key;
            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = "";
            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);
            // Compute the signature.
            signedXml.ComputeSignature();
            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            // Append the element to the XML document.
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        }
コード例 #11
0
        private System.Security.Cryptography.Xml.Signature SignXml(XmlDocument xmlDoc, RSA Key)
        {
            if (xmlDoc == null)
            {
                throw new ArgumentException(nameof(xmlDoc));
            }
            if (Key == null)
            {
                throw new ArgumentException(nameof(Key));
            }
            SignedXml signedXml = new SignedXml(xmlDoc);

            signedXml.SigningKey = (AsymmetricAlgorithm)Key;
            Reference reference = new Reference();

            reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform signatureTransform = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform((Transform)signatureTransform);
            signedXml.AddReference(reference);
            signedXml.ComputeSignature();
            XmlElement xml = signedXml.GetXml();

            System.Security.Cryptography.Xml.Signature signature = signedXml.Signature;
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode((XmlNode)xml, true));
            return(signature);
        }
コード例 #12
0
ファイル: TSTest.cs プロジェクト: darkogele/Rabota
        public static string SignXml(XmlDocument xmlDoc, X509Certificate2 cert)
        {
            var rsaKey = (RSACryptoServiceProvider)cert.PrivateKey;

            if (xmlDoc == null)
            {
                throw new ArgumentException("xmlDoc");
            }
            if (rsaKey == null)
            {
                throw new ArgumentException("Key");
            }

            var signedXml    = new SignedXml(xmlDoc);
            var XMLSignature = signedXml.Signature;

            signedXml.SigningKey = rsaKey;
            var reference = new Reference();

            reference.Uri = "";
            var env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            signedXml.AddReference(reference);
            var keyInfo = new KeyInfo();

            keyInfo.AddClause(new KeyInfoX509Data(cert));
            XMLSignature.KeyInfo = keyInfo;
            signedXml.ComputeSignature();
            var xmlDigitalSignature = signedXml.GetXml();

            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
            return(xmlDoc.InnerXml);
        }
コード例 #13
0
        //public static object VerifyLicense(byte[] certPubKeyData, string licenseKey)
        //{

        //    string licenseString;
        //    object licenseInformation = null;
        //    try
        //    {
        //        X509Certificate2 certificate = new X509Certificate2(certPubKeyData);
        //        RSACryptoServiceProvider rsaCryptoServiceProvider = (RSACryptoServiceProvider)certificate.PublicKey.Key;
        //        XmlDocument xmlDocument = new XmlDocument
        //        {
        //            PreserveWhitespace = true
        //        };
        //        xmlDocument.LoadXml(Encoding.UTF8.GetString(Convert.FromBase64String(licenseKey)));
        //        if (VerifyXml(xmlDocument, rsaCryptoServiceProvider))
        //        {
        //            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");
        //            xmlDocument.DocumentElement.RemoveChild(nodeList[0]);
        //            licenseString = xmlDocument.OuterXml;
        //            XmlSerializer xmlSerializer = new XmlSerializer(typeof(object), new Type[] { typeof(object) });
        //            using (StringReader stringReader = new StringReader(licenseString))
        //            {
        //                licenseInformation = (object)xmlSerializer.Deserialize(stringReader);
        //            }
        //        }
        //    }
        //    catch (Exception)
        //    {
        //    }
        //    return licenseInformation;
        //}

        //private static Boolean VerifyXml(XmlDocument Doc, RSA Key)
        //{
        //    // Check arguments.
        //    if (Doc == null)
        //        throw new ArgumentException("Doc");
        //    if (Key == null)
        //        throw new ArgumentException("Key");

        //    // Create a new SignedXml object and pass it
        //    // the XML document class.
        //    SignedXml signedXml = new SignedXml(Doc);

        //    // Find the "Signature" node and create a new
        //    // XmlNodeList object.
        //    XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");

        //    // Throw an exception if no signature was found.
        //    if (nodeList.Count <= 0)
        //    {
        //        throw new CryptographicException("Verification failed: No Signature was found in the document.");
        //    }

        //    // This example only supports one signature for
        //    // the entire XML document.  Throw an exception
        //    // if more than one signature was found.
        //    if (nodeList.Count >= 2)
        //    {
        //        throw new CryptographicException("Verification failed: More that one signature was found for the document.");
        //    }

        //    // Load the first <signature> node.
        //    signedXml.LoadXml((XmlElement)nodeList[0]);

        //    // Check the signature and return the result.
        //    return signedXml.CheckSignature(Key);
        //}

        private static void SignXML(XmlDocument xmlDoc, RSA Key)
        {
            if (xmlDoc == null)
            {
                throw new ArgumentException("xmlDoc");
            }

            SignedXml signedXml = new SignedXml(xmlDoc)
            {
                SigningKey = Key ?? throw new ArgumentException("Key")
            };

            Reference reference = new Reference
            {
                Uri = ""
            };

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            signedXml.AddReference(reference);

            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        }
    }
コード例 #14
0
        public static SignedXml Standard(XmlDocument doc)
        {
            var signedXml = new SignedXml(doc)
            {
                SigningKey = RSA.Create(2048),
            };

            var signatureMethod = @"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

            signedXml.SignedInfo.SignatureMethod = signatureMethod;

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            signedXml.ComputeSignature();

            return(signedXml);
        }
コード例 #15
0
        public static void SignXml(XmlDocument xmlDoc, RSA rsaKey)
        {
            if (xmlDoc == null)
            {
                throw new ArgumentException(nameof(xmlDoc));
            }
            if (rsaKey == null)
            {
                throw new ArgumentException(nameof(rsaKey));
            }

            SignedXml signedXml = new SignedXml(xmlDoc);

            signedXml.SigningKey = rsaKey;

            Reference reference = new Reference();

            reference.Uri = "";

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            signedXml.AddReference(reference);

            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        }
コード例 #16
0
        /// <summary>
        /// Computes the hash value of the specified System.Xml.XmlDocument object.
        /// </summary>
        /// <param name="doc">The System.Xml.XmlDocument object to sign.</param>
        /// <returns>The System.Security.Cryptography.RSA signature as XmlElement</returns>
        public XmlElement RsaSignData(XmlDocument doc)
        {
            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(doc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = RsaProvider;
            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = "";
            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);
            // Compute the signature.
            signedXml.ComputeSignature();
            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            // Append the element to the XML document.
            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
            return(xmlDigitalSignature);
        }
コード例 #17
0
        public static XmlDocument SignXmlDocument(XmlDocument document, RSACryptoServiceProvider rsaProvider)
        {
            if (document == null)
            {
                throw new ArgumentException(nameof(document));
            }
            if (rsaProvider == null)
            {
                throw new ArgumentException(nameof(rsaProvider));
            }

            Reference reference = new Reference();

            reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            SignedXml signedXml = new SignedXml(document);

            signedXml.SigningKey = rsaProvider;
            signedXml.AddReference(reference);
            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            document.DocumentElement.AppendChild(document.ImportNode(xmlDigitalSignature, true));

            return(document);
        }
コード例 #18
0
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document.
        signedXml.SigningKey = Key;

        // Create a reference to be signed.
        Reference reference = new Reference();

        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

        reference.AddTransform(env);

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);


        // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();

        keyInfo.AddClause(new RSAKeyValue((RSA)Key));
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));


        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));

        doc.WriteTo(xmltw);
        xmltw.Close();
    }
        static string SignXml(RSA rsa, string xml)
        {
            var xmlDoc = new XmlDocument {
                PreserveWhitespace = true
            };

            xmlDoc.LoadXml(xml);

            var signedXml = new SignedXml(xmlDoc)
            {
                SigningKey = rsa
            };
            var reference = new Reference {
                Uri = ""
            };

            var env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            signedXml.AddReference(reference);
            signedXml.ComputeSignature();
            var xmlDigitalSignature = signedXml.GetXml();

            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
            return(xmlDoc.OuterXml);
        }
コード例 #20
0
        public static SignedXml Extended(XmlDocument doc)
        {
            var signatureMethod = @"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

            CryptoConfig.AddAlgorithm(typeof(DSSSignatureDescription), signatureMethod);

            var signedXml = new SignedXml(doc)
            {
                SigningKey = new DSS(),
            };

            signedXml.SignedInfo.SignatureMethod = signatureMethod;

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            signedXml.ComputeSignature();

            return(signedXml);
        }
コード例 #21
0
ファイル: XmlSigner.cs プロジェクト: wpq0/Document-Signer
        /// <summary>
        /// Sign
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="output">The output.</param>
        /// <param name="certificate">The certificate.</param>
        public override void Sign(Stream input, Stream output, X509Certificate2 certificate)
        {
            CheckInputOutputAndCertificate(input, output, certificate);

            using (var rsaKey = (RSACryptoServiceProvider)certificate.PrivateKey)
            {
                var xmlDoc = new XmlDocument {
                    PreserveWhitespace = true
                };
                xmlDoc.Load(input);
                var signedXml = new SignedXml(xmlDoc)
                {
                    SigningKey = rsaKey
                };
                var envelope  = new XmlDsigEnvelopedSignatureTransform();
                var reference = new Reference {
                    Uri = ""
                };
                reference.AddTransform(envelope);
                signedXml.AddReference(reference);
                signedXml.ComputeSignature();
                var xmlDigitalSignature = signedXml.GetXml();
                xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
                xmlDoc.Save(output);
            }
        }
コード例 #22
0
ファイル: XadesService.cs プロジェクト: yeco96/FE
        /// <summary>
        /// Inserta un contenido XML para generar una firma enveloped.
        /// </summary>
        /// <param name="xmlDocument"></param>
        private void SetContentEnveloped(SignatureDocument sigDocument, XmlDocument xmlDocument)
        {
            sigDocument.Document = xmlDocument;

            _refContent = new Reference();

            sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);

            _refContent.Id  = "Reference-" + Guid.NewGuid().ToString();
            _refContent.Uri = "";

            _dataFormat          = new DataObjectFormat();
            _dataFormat.MimeType = "text/xml";
            _dataFormat.Encoding = "UTF-8";

            for (int i = 0; i < sigDocument.Document.DocumentElement.Attributes.Count; i++)
            {
                if (sigDocument.Document.DocumentElement.Attributes[i].Name.Equals("id", StringComparison.InvariantCultureIgnoreCase))
                {
                    _refContent.Uri = "#" + sigDocument.Document.DocumentElement.Attributes[i].Value;
                    break;
                }
            }

            XmlDsigEnvelopedSignatureTransform xmlDsigEnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();

            _refContent.AddTransform(xmlDsigEnvelopedSignatureTransform);


            sigDocument.XadesSignature.AddReference(_refContent);
        }
コード例 #23
0
        private static void signXMLDocument(byte[] xmlDocumentBuffer, X509Certificate2 certificate, string signedXMLPath)
        {
            XmlDocument xmlDocument = new XmlDocument();
            string      xml         = Encoding.UTF8.GetString(xmlDocumentBuffer);

            xmlDocument.LoadXml(xml);

            using (var rsaKey = certificate.PrivateKey)
            {
                var signedXml = new SignedXml(xmlDocument);
                signedXml.SigningKey = rsaKey;

                var reference = new Reference();
                reference.Uri = "";

                var env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);

                signedXml.AddReference(reference);

                signedXml.ComputeSignature();

                var xmlDigitalSignature = signedXml.GetXml();

                xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(xmlDigitalSignature, true));

                xmlDocument.Save(signedXMLPath);
            }
        }
コード例 #24
0
        public static Transform fromURI(string uri)
        {
            Transform t = null;

            switch (uri)
            {
            case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315":
                t = new XmlDsigC14NTransform();
                break;

            case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments":
                t = new XmlDsigC14NWithCommentsTransform();
                break;

            case "http://www.w3.org/2000/09/xmldsig#enveloped-signature":
                t = new XmlDsigEnvelopedSignatureTransform();
                break;

            case "http://www.w3.org/TR/1999/REC-xpath-19991116":
                t = new XmlDsigXPathTransform();
                break;

            case "http://www.w3.org/TR/1999/REC-xslt-19991116":
                t = new XmlDsigXsltTransform();
                break;

            case "http://www.w3.org/2001/10/xml-exc-c14n#":
                t = new XmlDsigExcC14NTransform();
                break;
            }
            return(t);
        }
コード例 #25
0
        private static void SignXml(XmlDocument xmlDoc, AsymmetricAlgorithm key)
        {
            if (xmlDoc == null)
            {
                throw new ArgumentException("xmlDoc");
            }
            if (key == null)
            {
                throw new ArgumentException("key");
            }

            var signedXml = new SignedXml(xmlDoc)
            {
                SigningKey = key
            };

            var reference = new Reference {
                Uri = "#presented-form"
            };

            var env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            signedXml.AddReference(reference);
            //signedXml.ComputeSignature();
            //var xmlDigitalSignature = signedXml.GetXml();
            //xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));

            //xmlDoc.Save("out-signed-xml.xml");
        }
コード例 #26
0
ファイル: Prefeitura.cs プロジェクト: tiiselam/br02
        public XmlDocument GetXMLSigned(string MensagemXML, X509Certificate2 cert)
        {
            //return XML_Prefeitura.MensagemXML;
            try
            {
                XmlDocument xmlDoc = new XmlDocument();

                xmlDoc.LoadXml(MensagemXML);

                RSA rsaKey = ((RSA)cert.PrivateKey);

                // Sign the XML document.
                SignedXml signedXml = new SignedXml(xmlDoc);

                // Add the key to the SignedXml document.
                signedXml.SigningKey = rsaKey;

                // Create a reference to be signed.
                Reference reference = new Reference();
                reference.Uri = "";

                // Add an enveloped transformation to the reference.
                XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);

                KeyInfo         keyInfo     = new KeyInfo();
                KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert);
                //KeyInfoName kin = new KeyInfoName();
                //kin.Value = "Public key of certificate";
                //RSACryptoServiceProvider rsaprovider = (RSACryptoServiceProvider)cert.PublicKey.Key;
                //RSAKeyValue rkv = new RSAKeyValue(rsaprovider);
                // keyInfo.AddClause(kin);
                // keyInfo.AddClause(rkv);
                keyInfo.AddClause(keyInfoData);
                signedXml.KeyInfo = keyInfo;

                // Add the reference to the SignedXml object.
                signedXml.AddReference(reference);


                // Compute the signature.
                signedXml.ComputeSignature();



                // Get the XML representation of the signature and save
                // it to an XmlElement object.
                XmlElement xmlDigitalSignature = signedXml.GetXml();

                // Append the element to the XML document.
                xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));

                return(xmlDoc);
            }
            catch (Exception)
            {
                return(null);
            }
        }
コード例 #27
0
        public static bool SignXmlSHA256(XmlDocument docMsg, String cspName, String keyStorePhrass, X509Certificate2 signerCert, String referenceUri = "")
        {
            try
            {
                if (!String.IsNullOrEmpty(cspName))
                {
                    // Generate a signing key.
                    CspParameters csp = new CspParameters(1, cspName);
                    csp.Flags     = CspProviderFlags.UseDefaultKeyContainer;
                    csp.KeyNumber = (int)KeyNumber.Signature;

                    if (!String.IsNullOrEmpty(keyStorePhrass))
                    {
                        csp.KeyPassword = new SecureString();
                        foreach (var ch in keyStorePhrass.ToCharArray())
                        {
                            csp.KeyPassword.AppendChar(ch);
                        }
                    }

                    RSACryptoServiceProvider Key = new RSACryptoServiceProvider(csp);
                }

                SignedXml signedXml = new SignedXml(docMsg);
                signedXml.SigningKey = signerCert.PrivateKey;

                Reference reference = new Reference();
                reference.Uri          = referenceUri;
                reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

                //Add an enveloped transformation to the reference.
                XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);

                // Add the reference to the SignedXml object.
                signedXml.AddReference(reference);

                // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(signerCert));
                signedXml.KeyInfo = keyInfo;

                signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
                //signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigEnvelopedSignatureTransformUrl;
                signedXml.ComputeSignature();
                XmlElement xmlDigitalSignature = signedXml.GetXml();

                // Append the element to the XML document.
                docMsg.DocumentElement.AppendChild(docMsg.ImportNode(xmlDigitalSignature, true));

                return(true);
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }

            return(false);
        }
コード例 #28
0
        /// <summary>
        /// Signs the specified xmldocument with the given key and the finderprint.
        /// </summary>
        /// <param name="doc">The XMl representation of a request to iDeal</param>
        /// <param name="key">The key used to sign</param>
        /// <param name="fingerprintHex">The fingerprint</param>
        /// <returns>Returns the modified xml with the signature</returns>
        public static XmlElement Sign(ref XmlDocument doc, RSA key, string fingerprintHex)
        {
            doc.PreserveWhitespace = true;
            Trace.WriteLine("Message to sign:" + doc.OuterXml);
            SignedXml signedXml = new SignedXml(doc);

            signedXml.SigningKey = key;

            // Get the signature object from the SignedXml object.
            Signature signatureRef = signedXml.Signature;

            //Pass "" to specify that all of the current XML document should be signed.
            Reference reference = new Reference("");

            reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            // Add the Reference object to the Signature object.
            signatureRef.SignedInfo.AddReference(reference);

            signatureRef.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signatureRef.SignedInfo.SignatureMethod        = XmlDigSignRSASHA256Namespace;

            // Add an RSAKeyValue KeyInfo
            KeyInfo       keyInfo = new KeyInfo();
            KeyInfoClause clause  = new RSAKeyValue(key);

            keyInfo.AddClause(clause);
            signatureRef.KeyInfo = keyInfo;

            signedXml.ComputeSignature();
            XmlElement xmlSignature = signedXml.GetXml();

            // Append the element to the XML document.
            doc.DocumentElement.AppendChild(doc.ImportNode(xmlSignature, true));

            //xmlSignature.Prefix = "ds";
            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            string xml = doc.OuterXml;

            //replace KeyValue with KeyName containing the fingerprint of the signing certificate
            string keyNameTag = "<KeyName>" + fingerprintHex.Replace("-", "") + "</KeyName>";

            xml = System.Text.RegularExpressions.Regex.Replace(xml, "<KeyValue>.*</KeyValue>", keyNameTag);

            //reload the xml document from customized xml source
            doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.LoadXml(xml);
            //}
            return((XmlElement)doc.DocumentElement.ChildNodes[doc.DocumentElement.ChildNodes.Count - 1]);
        }
コード例 #29
0
        /// <summary>
        /// Sign an XML file.
        /// </summary>
        /// <param name="xmlDoc"> XML document object that holds the XML data</param>
        /// <param name="signingKey">The certificate which will be used in signing the XML document</param>
        /// <param name="addKey">Flag to indicate if the public key should be included in the signed XML document or not</param>
        /// <exception cref="ArgumentNullException">Private key is null or any of the passed arguments is null.</exception>
        /// <exception cref="CryptographicException">The key value is not an RSA key, or the key is unreadable.</exception>
        /// <exception cref="NotSupportedException">The key algorithm for this private key is not supported.</exception>
        /// <exception cref="CryptographicUnexpectedOperationException">The X.509 keys do not match.</exception>
        /// <exception cref="ArgumentException">The cryptographic service provider key is null.</exception>
        private static void SignXml(XmlDocument xmlDoc, X509Certificate2 signingKey, bool addKey)
        {
            if (signingKey == null)
            {
                throw new ArgumentNullException("signingKey is null");
            }

            // Create RSA signing key and save it in the container.
            RSACryptoServiceProvider key = signingKey.PrivateKey as RSACryptoServiceProvider;

            // Check arguments.
            if (xmlDoc == null)
            {
                throw new ArgumentNullException("xmlDoc is null");
            }
            if (key == null)
            {
                throw new ArgumentNullException("Private key is null");
            }

            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(xmlDoc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = key;

            // Add public key of the certificate
            if (addKey)
            {
                KeyInfo         keyInfo     = new KeyInfo();
                KeyInfoX509Data keyInfoData = new KeyInfoX509Data(signingKey);
                keyInfo.AddClause(keyInfoData);
                signedXml.KeyInfo = keyInfo;
            }

            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            // Append the element to the XML document.
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        }
コード例 #30
0
        public static void SignXml(XmlDocument xmlDoc, X509Certificate2 uidCert)
        {
            RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)uidCert.PrivateKey;


            // Check arguments.
            if (xmlDoc == null)
            {
                throw new ArgumentException("xmlDoc");
            }
            if (rsaKey == null)
            {
                throw new ArgumentException("Key");
            }

            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(xmlDoc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = rsaKey;


            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);


            // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
            KeyInfo keyInfo = new KeyInfo();

            KeyInfoX509Data clause = new KeyInfoX509Data();

            clause.AddSubjectName(uidCert.Subject);
            clause.AddCertificate(uidCert);
            keyInfo.AddClause(clause);
            signedXml.KeyInfo = keyInfo;

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            System.Console.WriteLine(signedXml.GetXml().InnerXml);

            // Append the element to the XML document.
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        }
コード例 #31
0
        /// <summary>
        ///     Obtém a assinatura de um objeto serializável
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objeto"></param>
        /// <param name="id"></param>
        /// <param name="certificadoDigital">Informe o certificado digital</param>
        /// <param name="manterDadosEmCache">Validador para manter o certificado em cache</param>
        /// <returns>Retorna um objeto do tipo Classes.Assinatura.Signature, contendo a assinatura do objeto passado como parâmetro</returns>
        public static Signature ObterAssinatura <T>(T objeto, string id, X509Certificate2 certificadoDigital, bool manterDadosEmCache = false, string signatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1", string digestMethod = "http://www.w3.org/2000/09/xmldsig#sha1") where T : class
        {
            var objetoLocal = objeto;

            if (id == null)
            {
                throw new Exception("Não é possível assinar um objeto evento sem sua respectiva Id!");
            }

            try
            {
                var documento = new XmlDocument {
                    PreserveWhitespace = true
                };
                documento.LoadXml(FuncoesXml.ClasseParaXmlString(objetoLocal));
                var docXml = new SignedXml(documento)
                {
                    SigningKey = certificadoDigital.PrivateKey
                };

                docXml.SignedInfo.SignatureMethod = signatureMethod;

                var reference = new Reference {
                    Uri = "#" + id, DigestMethod = digestMethod
                };

                // adicionando EnvelopedSignatureTransform a referencia
                var envelopedSigntature = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(envelopedSigntature);

                var c14Transform = new XmlDsigC14NTransform();
                reference.AddTransform(c14Transform);

                docXml.AddReference(reference);

                // carrega o certificado em KeyInfoX509Data para adicionar a KeyInfo
                var keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(certificadoDigital));

                docXml.KeyInfo = keyInfo;
                docXml.ComputeSignature();

                //// recuperando a representação do XML assinado
                var xmlDigitalSignature = docXml.GetXml();
                var assinatura          = FuncoesXml.XmlStringParaClasse <Signature>(xmlDigitalSignature.OuterXml);
                return(assinatura);
            }
            finally
            {
                //Se não mantém os dados do certificado em cache e o certificado não foi passado por parâmetro(isto é, ele foi criado dentro deste método),
                //então libera o certificado, chamando o método reset.
                if (!manterDadosEmCache & certificadoDigital == null)
                {
                    certificadoDigital.Reset();
                }
            }
        }
コード例 #32
0
        /// <summary>
        /// Verified the xml with the physical Certificate
        /// </summary>
        /// <param name="xmlDoc"> xml document</param>
        /// <param name="certificateFileName"> Certificate File Name</param>
        /// <returns>Boolean Value</returns>
        public static bool IsXmlSignValidByFile(XmlDocument xmlDoc, string certificateFileName)
        {
            CryptoConfig.AddAlgorithm(typeof(Security.Cryptography.RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
            CspParameters cspParams = new CspParameters();

            cspParams.KeyContainerName = "XML_DSIG_RSA_KEY";
            RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);

            if (xmlDoc == null)
            {
                throw new CryptographicException("XML Document object cann't be null");
            }

            X509Certificate2 x509;

            // Add SHA-256 algorith mapping.
            CryptoConfig.AddAlgorithm(typeof(Security.Cryptography.RSAPKCS1SHA256SignatureDescription), XmlDsigSha256SignatureMethod);

            // Create a new x509 instance based on the passed in certificate.
            try
            {
                x509 = new X509Certificate2(certificateFileName, string.Empty, X509KeyStorageFlags.Exportable);
            }
            catch
            {
                throw new CryptographicException("Could not load the certificate file at " + certificateFileName);
            }

            // loading the key string
            csp.FromXmlString(x509.PublicKey.Key.ToXmlString(false));
            xmlDoc.PreserveWhitespace = true;

            SignedXml signedXml = new SignedXml(xmlDoc);

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;
            signedXml.SignedInfo.SignatureMethod        = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            signedXml.SigningKey = csp;

            // Create a reference to be signed.
            Reference reference = new Reference(string.Empty);

            reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(false);

            reference.AddTransform(env);
            signedXml.AddReference(reference);

            // Find the "Signature" node and create a new
            XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Signature");

            // Load the first <signature> node.
            signedXml.LoadXml((XmlElement)nodeList[0]);

            return(signedXml.CheckSignature(csp));
        }
    public static void Main(String[] args)
    {
        //calculate caninicalized xml

        var t = new XmlDsigEnvelopedSignatureTransform(false);
        XmlDocument doc = new XmlDocument();
        //doc.PreserveWhitespace = true;
        doc.Load(@"c:\temp\x.xml");
        t.LoadInput(doc);

        FieldInfo field = t.GetType().GetField("_signaturePosition",
                         BindingFlags.NonPublic |
                         BindingFlags.Instance);

        field.SetValue(t, 1);

        var res = (XmlDocument)t.GetOutput();
        var s = res.OuterXml;

        var c14 = new XmlDsigC14NTransform();
        c14.LoadInput(res);
        var mem = (MemoryStream)c14.GetOutput();

        var sha = new SHA256Managed();

        var byte1 = c14.GetDigestedOutput(new SHA256Managed());
        var digest1 = Convert.ToBase64String(byte1);
        var byte2 = sha.ComputeHash(mem.ToArray());
        var digest2 = Convert.ToBase64String(byte2);

        var s1 = System.Text.Encoding.UTF8.GetString(mem.ToArray());
        var byte3 = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(s1));
        var digest3 = Convert.ToBase64String(byte3);

        //return;

        //validate signature

        CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(@"c:\temp\x.xml");
        XmlNode node = xmlDoc.DocumentElement;
        X509Certificate2 cert = new X509Certificate2(File.ReadAllBytes(@"c:\temp\x.cer"));
        bool isValid = ValidateXml(xmlDoc, cert);
        //return;

        //calc hash
        var sha1 = new SHA256Managed();
        var b1 = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(File.ReadAllText(@"c:\temp\x_no_sig.xml")));
        var b64 = Convert.ToBase64String(b1);
    }
コード例 #34
0
ファイル: XmlDigitalSigner.cs プロジェクト: brooklynb7/CGA
    // Sign an XML file.This document cannot be verified unless the verifying code has the key with which it was signed.
    public static void SignXml(XmlDocument doc, RSA key)
    {
        // Create a SignedXml object
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document
        signedXml.KeyInfo = new KeyInfo();
        signedXml.KeyInfo.AddClause(new RSAKeyValue(key));
        signedXml.SigningKey = key;

        // Create a reference to be signed
        Reference reference = new Reference("");

           // reference.Uri = "";

        // Add an enveloped transformation to the reference
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

        reference.AddTransform(env);

        // Set the KeyInfo to the SignedXml object
           //     KeyInfo ki = new KeyInfo();

        //    ki.AddClause(new RSAKeyValue(key));

         //   signedXml.SigningKey = key;
        //    signedXml.KeyInfo = ki;

        // Add the reference to the SignedXml object
        signedXml.AddReference(reference);

        // Compute the signature
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save it to an XmlElement object.
         //   XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document
          //  doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
        doc.DocumentElement.PrependChild(signedXml.GetXml());
    }
コード例 #35
0
	public static XmlDocument Assinar(XmlDocument docXML, string pUri, X509Certificate2 pCertificado)
	{
		try {
			// Load the certificate from the certificate store.
			X509Certificate2 cert = pCertificado;

			// Create a new XML document.
			XmlDocument doc = new XmlDocument();

			// Format the document to ignore white spaces.
			doc.PreserveWhitespace = false;

			// Load the passed XML file using it's name.
			doc = docXML;

			// Create a SignedXml object.
			SignedXml signedXml = new SignedXml(doc);

			// Add the key to the SignedXml document.
			signedXml.SigningKey = cert.PrivateKey;

			// Create a reference to be signed.
			Reference reference = new Reference();
			// pega o uri que deve ser assinada
			XmlAttributeCollection _Uri = doc.GetElementsByTagName(pUri).Item(0).Attributes;
			foreach (XmlAttribute _atributo in _Uri) {
				if (_atributo.Name == "Id") {
					reference.Uri = "#" + _atributo.InnerText;
				}
			}

			// Add an enveloped transformation to the reference.
			XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
			reference.AddTransform(env);

			XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
			reference.AddTransform(c14);

			// Add the reference to the SignedXml object.
			signedXml.AddReference(reference);

			// Create a new KeyInfo object.
			KeyInfo keyInfo = new KeyInfo();

			// Load the certificate into a KeyInfoX509Data object
			// and add it to the KeyInfo object.
			keyInfo.AddClause(new KeyInfoX509Data(cert));

			// Add the KeyInfo object to the SignedXml object.
			signedXml.KeyInfo = keyInfo;

			// Compute the signature.
			signedXml.ComputeSignature();

			// Get the XML representation of the signature and save
			// it to an XmlElement object.
			XmlElement xmlDigitalSignature = signedXml.GetXml();

			// Append the element to the XML document.
			doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));


			if (doc.FirstChild is XmlDeclaration) {
				doc.RemoveChild(doc.FirstChild);
			}

			return doc;
		} catch (Exception ex) {
			throw new Exception("Erro ao efetuar assinatura digital, detalhes: " + ex.Message);
		}
	}
コード例 #36
0
    //-------------------------------------------------------------------------------------------
    private string SignXML(string xml)
    {
        // Signing XML Documents: http://msdn.microsoft.com/en-us/library/ms229745.aspx

          var rsaKey = new RSACryptoServiceProvider();
          string sales_licensekeys_privatekey = ConfigurationManager.AppSettings["sales_licensekeys_privatekey"];
          if (!File.Exists(sales_licensekeys_privatekey))
               throw new Exception("The private signing key is missing");
          rsaKey.FromXmlString(System.IO.File.ReadAllText(sales_licensekeys_privatekey));

          XmlDocument doc = new XmlDocument();
          doc.PreserveWhitespace = true;
          doc.LoadXml(xml);

          SignedXml signedXml = new SignedXml(doc);
          signedXml.SigningKey = rsaKey;

          // Create a reference to be signed.
          Reference reference = new Reference();
          reference.Uri = ""; // set to "" to sign the entire doc

          XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
          reference.AddTransform(env);

          signedXml.AddReference(reference);
          signedXml.ComputeSignature();

          XmlElement xmlDigitalSignature = signedXml.GetXml();

          doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

          MemoryStream ms = new MemoryStream();
          XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding(false));
          writer = new XmlTextWriter(ms, new UTF8Encoding(false));
          //writer.Formatting = Formatting.Indented;

          doc.WriteContentTo(writer);
          writer.Flush();
          ms.Position = 0;
          StreamReader reader = new StreamReader(ms);
          return reader.ReadToEnd();
    }
コード例 #37
0
ファイル: Utils.cs プロジェクト: isdoc/dsig-demo
    // Třída podepíše certifikátem dokument XML
    // Pokud je již dokument podepsaný, přidá se další podpis
    public XmlDocument Sign(XmlDocument doc, X509Certificate2 cert)
    {
        // před podepisováním z dokumentu odstraníme komentáře (.NET s nimi má problémy pokud se kombinují s XPath transformacemi)
        XmlDocument strippedDoc = RemoveComments(doc);

        // definice mapování prefixů na jmenné prostory
        XmlNamespaceManager manager = new XmlNamespaceManager(strippedDoc.NameTable);
        manager.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");

        // zjištění kolik podpisů již v dokumentu je
        int signatures = strippedDoc.SelectNodes("//dsig:Signature", manager).Count;

        // objekt sloužící pro vytvoření podpisu
        SignedXml signedXml = new SignedXml(strippedDoc);

        // podepisovat budeme privátním klíčem z certifikátu
        signedXml.SigningKey = cert.PrivateKey;

        // podepisovat budeme pomocí RSA-SHA256
        signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

        // reference na podepisovaný dokument ("" znamená celý dokument)
        Reference reference = new Reference();
        reference.Uri = "";

        // pro výpočet otisku se bude používat SHA-256
        reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        // digitální podpis bude přímo součástí dokumentu XML (tzv. "enveloped signature")
        XmlDsigEnvelopedSignatureTransform envTransform = new XmlDsigEnvelopedSignatureTransform();
        reference.AddTransform(envTransform);

        // navíc budeme používat XPath transoformaci, která dovoluje přidat několik podpisů najednou
        XmlDsigXPathTransform xpathTransform = new XmlDsigXPathTransform();

        // příprava definice XPath transformace jako struktura XML signature
        XmlDocument transformBody = new XmlDocument();

        // podoba XPath filtru se liší podle počtu podpisů
        if (signatures == 0)
            transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature)</dsig:XPath>");
        else
            transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature) or not(ancestor-or-self::dsig:Signature/preceding-sibling::dsig:Signature[" + signatures + "])</dsig:XPath>");

        // načtení definice XPath transformace do objektu
        xpathTransform.LoadInnerXml(transformBody.SelectNodes("/*[1]"));
        
        // přidání XPath transformace
        reference.AddTransform(xpathTransform);

        // přidání reference do podpisu
        signedXml.AddReference(reference);

        // přidání certifikátu do podpisu
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(new KeyInfoX509Data(cert));
        signedXml.KeyInfo = keyInfo;

        // výpočet podpisu
        signedXml.ComputeSignature();

        // získání XML reprezentace podpisu
        XmlElement xmlSignature = signedXml.GetXml();

        // k podpisu přidáme identifikátor, tak jak doporučuje standard ISDOC
        xmlSignature.SetAttribute("Id", "Signature-" + (signatures + 1));

        // XML dokument pro podepsaný výsledek
        XmlDocument result = new XmlDocument();

        // bílé znaky musíme zachovat, jinak se špatně spočte hash
        result.PreserveWhitespace = true;               

        // načtení původního dokumentu
        result.AppendChild(result.ImportNode(strippedDoc.DocumentElement, true));

        // připojení podpisu na konec dokumentu XML
        result.DocumentElement.AppendChild(result.ImportNode(xmlSignature, true));

        return result;
    }
コード例 #38
0
        private void Sign(Message message, string[] elementIdsToSign, string[] attachmentsToSign, string wssNamespace,
            X509Certificate2 certificate)
        {
            //Prepare XML to encrypt and sign
            var element = this.PrepareEncyrptSign(message);

            bool signEntireDocument = true;
            string elementToBeSigned = string.Empty;
            var signedMessage = new XmlDocument();
            signedMessage.AppendChild(signedMessage.ImportNode(element, true));

            SignatureType signAs = SignatureType.InternallyDetached;
            signedMessage.PreserveWhitespace = false;

            OverrideSignedXml signedXml = new OverrideSignedXml(signedMessage);
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            if (elementIdsToSign != null && elementIdsToSign.Length > 0)
            {
                bool isContentTransform = this.IsSignatureContentTransform;

                foreach (string s in elementIdsToSign)
                {
                    // Create a reference to be signed.
                    Reference reference = new Reference(string.Format("#{0}", s));
                    reference.AddTransform(new XmlDsigExcC14NTransform());
                    reference.DigestMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

                    // Add the reference to the SignedXml object.
                    signedXml.AddReference(reference);
                }

                signEntireDocument = false;
            }

            // Reference attachments to sign
            if (attachmentsToSign != null && attachmentsToSign.Length > 0)
            {
                bool isContentTransform = this.IsSignatureContentTransform;

                foreach (string attachmentId in attachmentsToSign)
                {
                    // Create a reference to be signed.
                    Reference reference = new Reference(string.Format("{0}{1}", Constants.CidUriScheme, attachmentId));
                    reference.DigestMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

                    if (isContentTransform)
                    {
                        AttachmentContentSignatureTransform env = new AttachmentContentSignatureTransform();
                        reference.AddTransform(env);
                    }
                    else
                    {
                        AttachmentCompleteSignatureTransform env = new AttachmentCompleteSignatureTransform();
                        reference.AddTransform(env);
                    }

                    // Add the reference to the SignedXml object.
                    signedXml.AddReference(reference);
                }

                signEntireDocument = false;
            }

            if (signEntireDocument)
            {
                Reference reference = new Reference();
                reference.Uri = "";
                reference.DigestMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

                XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);
                signedXml.AddReference(reference);
                signAs = SignatureType.Enveloped;
            }

            string x509CertificateReferenceId = string.Format("{0}-{1}", Constants.IdAttributeName,
                Guid.NewGuid().ToString("N"));
            KeyInfo keyInfo = new KeyInfo();
            keyInfo.AddClause(new KeyInfoX509SecurityTokenReference(string.Format("#{0}", x509CertificateReferenceId),
                wssNamespace));
            signedXml.KeyInfo = keyInfo;
            signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

            RSA key = (RSACryptoServiceProvider) certificate.PrivateKey;
            signedXML.SigningKey = key;
            CidWebRequest.Message = message;

            signedXml.ComputeSignature();
            var xmlSignature = signedXml.GetXml();
            XmlDocument unsignedEnvelopeDoc = new XmlDocument();
            unsignedEnvelopeDoc.LoadXml(message.MessageAsString);
        }
コード例 #39
0
ファイル: Utils.cs プロジェクト: isdoc/dsig-demo
    // Třída podepíše certifikátem dokument XML a přidá časové razítko
    // Pokud je již dokument podepsaný, přidá se další podpis
    public XmlDocument SignWithTimestamp(XmlDocument doc, X509Certificate2 cert, string tsURL, string tsUsername, string tsPassword)
    {
        // před podepisováním z dokumentu odstraníme komentáře (.NET s nimi má problémy pokud se kombinují s XPath transformacemi)
        XmlDocument strippedDoc = RemoveComments(doc);

        // definice mapování prefixů na jmenné prostory
        XmlNamespaceManager manager = new XmlNamespaceManager(strippedDoc.NameTable);
        manager.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");

        // zjištění kolik podpisů již v dokumentu je
        int signatures = strippedDoc.SelectNodes("//dsig:Signature", manager).Count;

        string signatureID = (signatures + 1).ToString();

        // vytvoření elementu Object pro časové razítko
        XmlElement objectElement = doc.CreateElement("Object", "http://www.w3.org/2000/09/xmldsig#");

        // spočítání otisku certifikátu
        SHA256 sha256 = new SHA256Managed();
        string certHash = Convert.ToBase64String(sha256.ComputeHash(cert.GetRawCertData()));

        objectElement.InnerXml = @"<xades:QualifyingProperties xmlns:xades='http://uri.etsi.org/01903/v1.3.2#' Target='#Signature-" + signatureID + @"' xmlns='http://www.w3.org/2000/09/xmldsig#'>
                <xades:SignedProperties Id='Signature-" + signatureID + @"-SignedProperties'>
                  <xades:SignedSignatureProperties>
                    <xades:SigningTime>" + XmlConvert.ToString(DateTime.Now.ToUniversalTime(), XmlDateTimeSerializationMode.RoundtripKind) + @"</xades:SigningTime>
                    <xades:SigningCertificate>
                      <xades:Cert>
                        <xades:CertDigest>
                          <DigestMethod Algorithm='http://www.w3.org/2001/04/xmlenc#sha256'></DigestMethod>
                          <DigestValue>" + certHash + @"</DigestValue>
                        </xades:CertDigest>
                        <xades:IssuerSerial>
                          <X509IssuerName>" + cert.IssuerName + @"</X509IssuerName>
                          <X509SerialNumber>" + cert.GetSerialNumberString() + @"</X509SerialNumber>
                        </xades:IssuerSerial>
                      </xades:Cert>
                    </xades:SigningCertificate>
                  </xades:SignedSignatureProperties>
                  <xades:SignedDataObjectProperties>
                    <xades:DataObjectFormat ObjectReference='#Signature-" + signatureID + @"-Document-Reference'>
                      <xades:MimeType>application/xml</xades:MimeType>
                    </xades:DataObjectFormat>
                  </xades:SignedDataObjectProperties>
                </xades:SignedProperties>
                <xades:UnsignedProperties>
                  <xades:UnsignedSignatureProperties>
                    <xades:SignatureTimeStamp>
                      <xades:EncapsulatedTimeStamp Encoding='http://uri.etsi.org/01903/v1.2.2#DER'></xades:EncapsulatedTimeStamp>
                    </xades:SignatureTimeStamp>
                  </xades:UnsignedSignatureProperties>
                </xades:UnsignedProperties>
               </xades:QualifyingProperties>";


        // objekt sloužící pro vytvoření podpisu
        CustomIdSignedXml signedXml = new CustomIdSignedXml(strippedDoc, objectElement);

        // podepisovat budeme privátním klíčem z certifikátu
        signedXml.SigningKey = cert.PrivateKey;

        // podepisovat budeme pomocí RSA-SHA256
        signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

        // reference na podepisovaný dokument ("" znamená celý dokument)
        Reference reference = new Reference();
        reference.Uri = "";
        reference.Id = "Signature-" + signatureID + "-Document-Reference";

        // pro výpočet otisku se bude používat SHA-256
        reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        // digitální podpis bude přímo součástí dokumentu XML (tzv. "enveloped signature")
        XmlDsigEnvelopedSignatureTransform envTransform = new XmlDsigEnvelopedSignatureTransform();
        reference.AddTransform(envTransform);

        // navíc budeme používat XPath transoformaci, která dovoluje přidat několik podpisů najednou
        XmlDsigXPathTransform xpathTransform = new XmlDsigXPathTransform();

        // příprava definice XPath transformace jako struktura XML signature
        XmlDocument transformBody = new XmlDocument();

        // podoba XPath filtru se liší podle počtu podpisů
        if (signatures == 0)
            transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature)</dsig:XPath>");
        else
            transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature) or not(ancestor-or-self::dsig:Signature/preceding-sibling::dsig:Signature[" + signatures + "])</dsig:XPath>");

        // načtení definice XPath transformace do objektu
        xpathTransform.LoadInnerXml(transformBody.SelectNodes("/*[1]"));

        // přidání XPath transformace
        reference.AddTransform(xpathTransform);

        // přidání reference do podpisu
        signedXml.AddReference(reference);

        // reference na SignedProperties -- XAdES-BES vyžaduje podpis certifikátu
        Reference spReference = new Reference();
        spReference.Uri = "#Signature-" + signatureID + "-SignedProperties";

        // pro výpočet otisku se bude používat SHA-256
        spReference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        // přidání reference do podpisu
        signedXml.AddReference(spReference);

        // přidání certifikátu do podpisu
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(new KeyInfoX509Data(cert));
        signedXml.KeyInfo = keyInfo;

        // přidání objektu s časovým razítkem do podpisu
        DataObject dataObj = new DataObject();
        dataObj.LoadXml(objectElement);
        signedXml.AddObject(dataObj);

        // výpočet podpisu
        signedXml.ComputeSignature();

        // získání XML reprezentace podpisu
        XmlElement xmlSignature = signedXml.GetXml();

        // k podpisu přidáme identifikátor, tak jak doporučuje standard ISDOC
        xmlSignature.SetAttribute("Id", "Signature-" + signatureID);

        // XML dokument pro podepsaný výsledek
        XmlDocument result = new XmlDocument();

        // bílé znaky musíme zachovat, jinak se špatně spočte hash
        result.PreserveWhitespace = true;

        // načtení původního dokumentu
        result.AppendChild(result.ImportNode(strippedDoc.DocumentElement, true));

        // připojení podpisu na konec dokumentu XML
        result.DocumentElement.AppendChild(result.ImportNode(xmlSignature, true));

        // Spočítání otisku digitálního podpisu
        byte[] digest;
        digest = sha256.ComputeHash(signedXml.SignatureValue);

        // generátor požadavků na časové razítko
        TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

        // vytvoření dat pro požadavek na timestamp server
        TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha256, digest);

        // získání surových dat pro poslání na timestamp server
        byte[] reqData = request.GetEncoded();

        // inicializace požadavku na timestamp server
        HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(tsURL);
        httpReq.Method = "POST";
        httpReq.ContentType = "application/timestamp-query";
        httpReq.ContentLength = reqData.Length;
        httpReq.Credentials = new NetworkCredential(tsUsername, tsPassword);

        // odeslání požadavku na timestamp server
        Stream reqStream = httpReq.GetRequestStream();
        reqStream.Write(reqData, 0, reqData.Length);
        reqStream.Close();

        // přečtení odpovědi
        HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
        Stream respStream = new BufferedStream(httpResp.GetResponseStream());
        TimeStampResponse response = new TimeStampResponse(respStream);
        respStream.Close();
        
        // Console.WriteLine("Status razítkování: " + response.Status);
        // Console.WriteLine("Čas razítka: " + response.TimeStampToken.TimeStampInfo.GenTime.ToLocalTime());
        string timestamp = Convert.ToBase64String(response.GetEncoded());

        // doplnění získaného časového razítka do dokumentu
        XmlNamespaceManager nsmng = new XmlNamespaceManager(result.NameTable);
        nsmng.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
        nsmng.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#");
        XmlElement etsElement = (XmlElement)result.SelectSingleNode("//*[@Id = 'Signature-" + signatureID +"']/ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:SignatureTimeStamp/xades:EncapsulatedTimeStamp", nsmng);
        etsElement.InnerText = timestamp;

        return result;
    }