public override object EncodeCMS(X509Certificate2 certificate, string xmlFilePath) { XmlDocument Document = new XmlDocument(); Document.PreserveWhitespace = true; XmlTextReader XmlFile = new XmlTextReader(xmlFilePath); Document.Load(XmlFile); XmlFile.Close(); XmlNodeList SignaturesList = Document.GetElementsByTagName("Signature"); // Remove existing signatures, this is not a countersigning. for (int i = 0; i < SignaturesList.Count; i++) { SignaturesList[i].ParentNode.RemoveChild(SignaturesList[i]); i--; } SignedXml SignedXml = new SignedXml(Document); SignedXml.SigningKey = certificate.PrivateKey; Reference Reference = new Reference(); Reference.Uri = ""; XmlDsigEnvelopedSignatureTransform EnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform(); Reference.AddTransform(EnvelopedSignatureTransform); SignedXml.AddReference(Reference); KeyInfo Key = new KeyInfo(); Key.AddClause(new KeyInfoX509Data(certificate)); SignedXml.KeyInfo = Key; SignedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement XmlDigitalSignature = SignedXml.GetXml(); return XmlDigitalSignature; }
// 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)); }
private static string SignXml(XmlDocument unsignedXml, AsymmetricAlgorithm key) { if (unsignedXml.DocumentElement == null) { throw new ArgumentNullException("unsignedXml"); } // Create a reference to be signed. Blank == Everything var emptyReference = new Reference { Uri = "" }; // Add an enveloped transformation to the reference. var envelope = new XmlDsigEnvelopedSignatureTransform(); emptyReference.AddTransform(envelope); var signedXml = new SignedXml(unsignedXml) { SigningKey = key }; signedXml.AddReference(emptyReference); signedXml.ComputeSignature(); var digitalSignature = signedXml.GetXml(); unsignedXml.DocumentElement.AppendChild( unsignedXml.ImportNode(digitalSignature, true)); var signedXmlOut = new StringBuilder(); using (var swOut = new StringWriter(signedXmlOut)) { unsignedXml.Save(swOut); } return signedXmlOut.ToString(); }
public void FullChain () { TransformChain chain = new TransformChain (); XmlDsigBase64Transform base64 = new XmlDsigBase64Transform (); chain.Add (base64); AssertEquals ("XmlDsigBase64Transform", base64, chain[0]); AssertEquals ("count 1", 1, chain.Count); XmlDsigC14NTransform c14n = new XmlDsigC14NTransform (); chain.Add (c14n); AssertEquals ("XmlDsigC14NTransform", c14n, chain[1]); AssertEquals ("count 2", 2, chain.Count); XmlDsigC14NWithCommentsTransform c14nc = new XmlDsigC14NWithCommentsTransform (); chain.Add (c14nc); AssertEquals ("XmlDsigC14NWithCommentsTransform", c14nc, chain[2]); AssertEquals ("count 3", 3, chain.Count); XmlDsigEnvelopedSignatureTransform esign = new XmlDsigEnvelopedSignatureTransform (); chain.Add (esign); AssertEquals ("XmlDsigEnvelopedSignatureTransform", esign, chain[3]); AssertEquals ("count 4", 4, chain.Count); XmlDsigXPathTransform xpath = new XmlDsigXPathTransform (); chain.Add (xpath); AssertEquals ("XmlDsigXPathTransform", xpath, chain[4]); AssertEquals ("count 5", 5, chain.Count); XmlDsigXsltTransform xslt = new XmlDsigXsltTransform (); chain.Add (xslt); AssertEquals ("XmlDsigXsltTransform", xslt, chain[5]); AssertEquals ("count 6", 6, chain.Count); }
public void FullChain () { TransformChain chain = new TransformChain (); XmlDsigBase64Transform base64 = new XmlDsigBase64Transform (); chain.Add (base64); Assert.AreEqual (base64, chain[0], "XmlDsigBase64Transform"); Assert.AreEqual (1, chain.Count, "count 1"); XmlDsigC14NTransform c14n = new XmlDsigC14NTransform (); chain.Add (c14n); Assert.AreEqual (c14n, chain[1], "XmlDsigC14NTransform"); Assert.AreEqual (2, chain.Count, "count 2"); XmlDsigC14NWithCommentsTransform c14nc = new XmlDsigC14NWithCommentsTransform (); chain.Add (c14nc); Assert.AreEqual (c14nc, chain[2], "XmlDsigC14NWithCommentsTransform"); Assert.AreEqual (3, chain.Count, "count 3"); XmlDsigEnvelopedSignatureTransform esign = new XmlDsigEnvelopedSignatureTransform (); chain.Add (esign); Assert.AreEqual (esign, chain[3], "XmlDsigEnvelopedSignatureTransform"); Assert.AreEqual (4, chain.Count, "count 4"); XmlDsigXPathTransform xpath = new XmlDsigXPathTransform (); chain.Add (xpath); Assert.AreEqual (xpath, chain[4], "XmlDsigXPathTransform"); Assert.AreEqual (5, chain.Count, "count 5"); XmlDsigXsltTransform xslt = new XmlDsigXsltTransform (); chain.Add (xslt); Assert.AreEqual (xslt, chain[5], "XmlDsigXsltTransform"); Assert.AreEqual (6, chain.Count, "count 6"); }
public XmlDocument assinaturaXmlEnviar(XmlDocument _xml) { XmlDocument xmlDocAss = _xml; try { if (cert == null) throw new Exception("Nao foi encontrado o certificado: " + config.configNFCe.NomeCertificadoDigital); Reference reference = new Reference(); SignedXml docXML = new SignedXml(xmlDocAss); docXML.SigningKey = cert.PrivateKey; XmlAttributeCollection uri = xmlDocAss.GetElementsByTagName("infNFe").Item(0).Attributes; foreach (XmlAttribute atributo in uri) { if (atributo.Name == "Id") reference.Uri = "#" + atributo.InnerText; } XmlDsigEnvelopedSignatureTransform envelopedSigntature = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(envelopedSigntature); XmlDsigC14NTransform c14Transform = new XmlDsigC14NTransform(); reference.AddTransform(c14Transform); docXML.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(cert)); docXML.KeyInfo = keyInfo; docXML.ComputeSignature(); XmlElement xmlDigitalSignature = docXML.GetXml(); foreach (var _nfe in xmlDocAss.GetElementsByTagName("NFe").Cast<XmlElement>()) _nfe.AppendChild(xmlDocAss.ImportNode(xmlDigitalSignature, true)); xmlDocAss.PreserveWhitespace = true; return xmlDocAss; } catch (Exception e) { Utils.Logger.getInstance.error(e); return null; throw new Exception(e.ToString()); } }
public string SignXml(XDocument xml) { using (MemoryStream streamIn = new MemoryStream()) { xml.Save(streamIn); streamIn.Position = 0; // var rsaKey = (RSACryptoServiceProvider)_privateCertificate.PrivateKey; // Create rsa crypto provider from private key contained in certificate, weirdest cast ever!; // string sCertFileLocation = @"C:\plugins\idealtest\bin\Debug\certficate.pfx"; // X509Certificate2 certificate = new X509Certificate2(sCertFileLocation, "D3M@ast3rsR0cks"); RSA rsaKey = (RSACryptoServiceProvider)_privateCertificate.PrivateKey; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(streamIn); SignedXml signedXml = new SignedXml(xmlDoc); signedXml.SigningKey = rsaKey; Reference reference = new Reference(); reference.Uri = ""; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); KeyInfoName kin = new KeyInfoName(); kin.Value = _privateCertificate.Thumbprint; keyInfo.AddClause(kin); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); using (MemoryStream sout = new MemoryStream()) { xmlDoc.Save(sout); sout.Position = 0; using (StreamReader reader = new StreamReader(sout)) { string xmlOut = reader.ReadToEnd(); return xmlOut; } } } }
public string AssinarComCertificado(string textXML, X509Certificate2 certificado) { try { string xmlString = textXML; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = false; doc.LoadXml(xmlString); Reference reference = new Reference(); reference.Uri = ""; XmlDocument documentoNovo = new XmlDocument(); documentoNovo.LoadXml(doc.OuterXml); SignedXml signedXml = new SignedXml(documentoNovo); signedXml.SigningKey = certificado.PrivateKey; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); XmlDsigC14NTransform c14 = new XmlDsigC14NTransform(); reference.AddTransform(c14); signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificado)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); XmlNode sign = doc.ImportNode(xmlDigitalSignature, true); doc.ChildNodes.Item(0).AppendChild(sign); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.PreserveWhitespace = false; XMLDoc = doc; return XMLDoc.OuterXml; } catch (Exception error) { throw new Exception(error.Message); } }
public static XmlDocument SignDocument(XmlDocument doc) { //////////////// string signatureCanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#"; string signatureMethod = @"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; string digestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256"; string signatureReferenceURI = "#_73e63a41-156d-4fda-a26c-8d79dcade713"; CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), signatureMethod); X509Certificate2 signingCertificate = GetCertificate(); // /* add the following lines of code after var signingCertificate = GetCertificate();*/ CspParameters cspParams = new CspParameters(24); //cspParams.KeyContainerName = "XML_DISG_RSA_KEY"; RSACryptoServiceProvider key = new RSACryptoServiceProvider(cspParams); var strKey = signingCertificate.PrivateKey.ToXmlString(true); key.FromXmlString(strKey); /*assign the new key to signer's SigningKey */ //metadataSigner.SigningKey = key; // SignedXml signer = new SignedXml(doc); signer.SigningKey = key;//signingCertificate.PrivateKey; signer.KeyInfo = new KeyInfo(); signer.KeyInfo.AddClause(new KeyInfoX509Data(signingCertificate)); signer.SignedInfo.CanonicalizationMethod = signatureCanonicalizationMethod; signer.SignedInfo.SignatureMethod = signatureMethod; XmlDsigEnvelopedSignatureTransform envelopeTransform = new XmlDsigEnvelopedSignatureTransform(); XmlDsigExcC14NTransform cn14Transform = new XmlDsigExcC14NTransform(); Reference signatureReference = new Reference("#FATCA"); signatureReference.Uri = signatureReferenceURI; signatureReference.AddTransform(envelopeTransform); signatureReference.AddTransform(cn14Transform); signatureReference.DigestMethod = digestMethod; signer.AddReference(signatureReference); signer.ComputeSignature(); XmlElement signatureElement = signer.GetXml(); doc.DocumentElement.AppendChild(signer.GetXml()); return doc; }
public bool Execute() { Console.Out.WriteLine("Signing xml file"); Console.Out.WriteLine("input file = {0}", _inputFile); Console.Out.WriteLine("output file = {0}", _signatureFile); Console.Out.WriteLine("key file = {0}", _keyFile); using (var key = new RSACryptoServiceProvider()) { key.FromXmlString(File.ReadAllText(_keyFile)); var doc = new XmlDocument {PreserveWhitespace = true}; doc.Load(new XmlTextReader(_inputFile)); var signedXml = new SignedXml(doc) {SigningKey = key}; var xmlSignature = signedXml.Signature; var reference = new Reference(""); var env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); xmlSignature.SignedInfo.AddReference(reference); var keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue(key)); xmlSignature.KeyInfo = keyInfo; signedXml.ComputeSignature(); var xmlDigitalSignature = signedXml.GetXml(); using (var writer = new XmlTextWriter(_signatureFile, new UTF8Encoding(false))) { var signatureDocument = new XmlDocument(); var importNode = signatureDocument.ImportNode(xmlDigitalSignature, true); signatureDocument.AppendChild(importNode); signatureDocument.WriteTo(writer); writer.Close(); } } Console.Out.WriteLine("done"); return true; }
/// <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); } }
public static void SignSingleEntity( this GisGmp.Message message, X509Certificate2 certificate, XmlNode entityXml) { XmlDocument signingDoc = new XmlDocument(); signingDoc.LoadXml(entityXml.OuterXml); SmevSignedXml signedXml = new SmevSignedXml(signingDoc); signedXml.SigningKey = certificate.PrivateKey; Reference reference = new Reference(); reference.Uri = ""; reference.DigestMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3411UrlObsolete; XmlDsigEnvelopedSignatureTransform envelopedSignature = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(envelopedSignature); XmlDsigExcC14NTransform c14 = new XmlDsigExcC14NTransform(); reference.AddTransform(c14); KeyInfo ki = new KeyInfo(); ki.AddClause(new KeyInfoX509Data(certificate)); signedXml.KeyInfo = ki; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; signedXml.SignedInfo.SignatureMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3410UrlObsolete; signedXml.AddReference(reference); signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); signingDoc.DocumentElement.AppendChild(xmlDigitalSignature); XmlDocumentFragment signedFinalPayment = message.Xml.CreateDocumentFragment(); signedFinalPayment.InnerXml = signingDoc.OuterXml; var documentNode = entityXml.ParentNode; documentNode.RemoveChild(entityXml); documentNode.AppendChild(signedFinalPayment); }
public override string SignXml(XmlDocument Document) { SignedXmlWithId signedXml = new SignedXmlWithId(Document); signedXml.SigningKey = manager.Certificate.PrivateKey; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = ""; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true); reference.AddTransform(env); if (c14) { XmlDsigC14NTransform c14t = new XmlDsigC14NTransform(); reference.AddTransform(c14t); } KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(manager.Certificate); 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(); Document.DocumentElement.AppendChild( Document.ImportNode(xmlDigitalSignature, true)); return Document.OuterXml; }
public static string firmarDocumento(string documento, X509Certificate2 certificado) { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; String documento2 = documento; 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; }
private static void SignXml(XmlDocument Doc, RSA Key) { // Check arguments. if (Doc == null) throw new ArgumentException("Doc"); if (Key == null) throw new ArgumentException("Key"); SignedXml signedXml = new SignedXml(Doc); 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(); Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true)); }
/// <summary> /// 对传入xml文档对象进行签名 /// </summary> /// <param name="privateKey">私钥</param> /// <param name="signXmlDoc">待签名的xml文档对象</param> /// <returns>返回签名后的xml文本</returns> public static string Signature(string privateKey, string xmlString) { var _RSAProvider = new RSACryptoServiceProvider(keyLength); _RSAProvider.FromXmlString(privateKey); XmlDocument signXmlDoc = LoadXml(xmlString); // Create a SignedXml object. SignedXml signedXml = new SignedXml(signXmlDoc); // 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. signXmlDoc.DocumentElement.AppendChild(signXmlDoc.ImportNode(xmlDigitalSignature, true)); if (signXmlDoc.FirstChild is XmlDeclaration) { signXmlDoc.RemoveChild(signXmlDoc.FirstChild); } return FormatXml(signXmlDoc); }
/// <summary> /// Signs an XML Document for a Saml Response /// </summary> /// <param name="xml"></param> /// <param name="cert2"></param> /// <param name="referenceId"></param> /// <returns></returns> public static XmlElement SignDoc(XmlDocument doc, X509Certificate2 cert2, string referenceId, string referenceValue) { SamlSignedXml sig = new SamlSignedXml(doc, referenceId); // Add the key to the SignedXml xmlDocument. sig.SigningKey = cert2.PrivateKey; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = String.Empty; // reference.Uri = "#" + referenceValue; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); XmlDsigExcC14NTransform env2 = new XmlDsigExcC14NTransform(); reference.AddTransform(env); reference.AddTransform(env2); // Add the reference to the SignedXml object. sig.AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyData = new KeyInfoX509Data(cert2); keyInfo.AddClause(keyData); sig.KeyInfo = keyInfo; // Compute the signature. sig.ComputeSignature(); // Get the XML representation of the signature and save it to an XmlElement object. XmlElement xmlDigitalSignature = sig.GetXml(); return xmlDigitalSignature; }
/// <summary> /// Erzeugt für das übergebene XML-Dokument eine Signatur /// und fügt diese in das Dokument ein /// </summary> /// <param name="doc"></param> /// <returns></returns> public XmlDocument SignDocument(XmlDocument doc) { // Erstelle eine Referenz für die Transformation und // füge diese Referenz dem Signatur-Wrapper hinzu Reference reference = new Reference(); reference.Uri = String.Empty; XmlDsigEnvelopedSignatureTransform envelop = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(envelop); // Erstelle den Signatur-Wrapper mit Schlüsselinformationen SignedXml signedDoc = new SignedXml(doc); signedDoc.SigningKey = rsa; signedDoc.AddReference(reference); // Berechne die Signatur signedDoc.ComputeSignature(); // Füge die Signatur in das XML-Dokument ein und gebe es zurück doc.DocumentElement.AppendChild(doc.ImportNode(signedDoc.GetXml(), true)); return doc; }
void CheckProperties (XmlDsigEnvelopedSignatureTransform transform) { Assert.AreEqual ("http://www.w3.org/2000/09/xmldsig#enveloped-signature", transform.Algorithm, "Algorithm"); Type [] input = transform.InputTypes; Assert.AreEqual (3, input.Length, "Input Length"); // check presence of every supported input types bool istream = false; bool ixmldoc = false; bool ixmlnl = false; foreach (Type t in input) { if (t == typeof (XmlDocument)) ixmldoc = true; if (t == typeof (XmlNodeList)) ixmlnl = true; if (t == typeof (Stream)) istream = true; } Assert.IsTrue (istream, "Input Stream"); Assert.IsTrue (ixmldoc, "Input XmlDocument"); Assert.IsTrue (ixmlnl, "Input XmlNodeList"); Type [] output = transform.OutputTypes; Assert.AreEqual (2, output.Length, "Output Length"); // check presence of every supported output types bool oxmlnl = false; bool oxmldoc = false; foreach (Type t in output) { if (t == typeof (XmlNodeList)) oxmlnl = true; if (t == typeof (XmlDocument)) oxmldoc = true; } Assert.IsTrue (oxmlnl, "Output XmlNodeList"); Assert.IsTrue (oxmldoc, "Output XmlDocument"); }
// 给一个 xml 文件做签名的处理. // 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) { // Check arguments. if (Doc == null) throw new ArgumentException("Doc"); if (Key == null) throw new ArgumentException("Key"); // 创建一个新的 SignedXml 对象,并将 XmlDocument 对象传递给它。 SignedXml signedXml = new SignedXml(Doc); // 将签名 RSA 密钥添加到 SignedXml 对象。 signedXml.SigningKey = Key; // 创建说明签名内容的 Reference 对象。 若要对整个文档进行签名,请将 Uri 属性设置为 ""。 Reference reference = new Reference(); reference.Uri = ""; // 将 XmlDsigEnvelopedSignatureTransform 对象添加到 Reference 对象中。 // 变换使验证工具可以使用与签名工具所用的相同方式表示 XML 数据。 // XML 数据可以用不同方式表示,因此这一步对于验证来说至关重要。 XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // 将 Reference 对象添加到 SignedXml 对象中。 signedXml.AddReference(reference); // 通过调用 ComputeSignature 方法计算签名。 signedXml.ComputeSignature(); // 检索签名(一个 <Signature> 元素)的 XML 表示形式,并将它保存到一个新的 XmlElement 对象中。 XmlElement xmlDigitalSignature = signedXml.GetXml(); // 将元素追加到 XmlDocument 对象中。 Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true)); }
/// <summary> /// Gera assinatura Digital do XML /// </summary> /// <param name="XMLString"></param> /// <param name="RefUri"></param> /// <param name="X509Cert"></param> /// <returns></returns> public int Assinar(string XMLString, string RefUri, X509Certificate2 X509Cert) { int resultado = 0; msgResultado = "Assinatura realizada com sucesso"; try { // certificado para ser utilizado na assinatura // string _xnome = ""; bool bX509Cert = false; if (X509Cert != null) { _xnome = X509Cert.Subject.ToString(); } else { bX509Cert = true; } X509Certificate2 _X509Cert = new X509Certificate2(); X509Store store = new X509Store("MY", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectDistinguishedName, (object)_xnome, true); //if (collection1.Count == 0) if (bX509Cert) { resultado = 2; msgResultado = "Problemas no certificado digital"; } else { // certificado ok //_X509Cert = collection1[0]; _X509Cert = X509Cert; string x; x = _X509Cert.GetKeyAlgorithm().ToString(); // 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. try { doc.LoadXml(XMLString); // Verifica se a tag a ser assinada existe é única int qtdeRefUri = doc.GetElementsByTagName(RefUri).Count; if (qtdeRefUri == 0) { // a URI indicada não existe resultado = 4; msgResultado = "A tag de assinatura " + RefUri.Trim() + " inexiste"; } // Exsiste mais de uma tag a ser assinada else { if (qtdeRefUri > 1) { // existe mais de uma URI indicada resultado = 5; msgResultado = "A tag de assinatura " + RefUri.Trim() + " não é unica"; } else { try { //Claudinei - o.s. 23615 - 10/08/2009 //for (int i = 0; i < qtdeRefUri; i++) { //Fim - Claudinei - o.s. 23615 - 10/08/2009 // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); //sTipoAssinatura = _X509Cert.PrivateKey.KeySize.ToString(); // Add the key to the SignedXml document signedXml.SigningKey = _X509Cert.PrivateKey; // Create a reference to be signed Reference reference = new Reference(); // pega o uri que deve ser assinada XmlAttributeCollection _Uri = doc.GetElementsByTagName(RefUri).Item(0).Attributes; //Claudinei - o.s. 23615 - 10/08/2009 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(_X509Cert)); // Add the KeyInfo object to the SignedXml object. signedXml.KeyInfo = keyInfo; 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. //Claudinei - o.s. 23581 - 07/07/2009 /* string teste = ""; //XmlNode xmlno = new XmlNode(); foreach (XmlNode xmlno in doc) { teste = xmlno.Name.ToString(); } */ //Fim - Claudinei - o.s. 23581 - 07/07/2009 //Danner - o.s. 23732 - 11/11/2009 doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); //Fim - Danner - o.s. 23732 - 11/11/2009 XMLDoc = new XmlDocument(); XMLDoc.PreserveWhitespace = false; XMLDoc = doc; } //Claudinei - o.s. 23615 - 10/08/2009 } catch (Exception caught) { resultado = 7; msgResultado = "Erro: Ao assinar o documento - " + caught.Message; } } } } catch (Exception caught) { resultado = 3; msgResultado = "Erro: XML mal formado - " + caught.Message; } } } catch (Exception caught) { resultado = 1; msgResultado = "Erro: Problema ao acessar o certificado digital" + caught.Message; } return resultado; }
// creates a signed XML document with two certificates in the X509Data // element, with the second being the one that should be used to verify // the signature static XmlDocument CreateSignedXml (X509Certificate2 cert, string canonicalizationMethod, string lineFeed) { XmlDocument doc = CreateSomeXml (lineFeed); SignedXml signedXml = new SignedXml (doc); signedXml.SigningKey = cert.PrivateKey; signedXml.SignedInfo.CanonicalizationMethod = canonicalizationMethod; Reference reference = new Reference (); reference.Uri = ""; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform (); reference.AddTransform (env); signedXml.AddReference (reference); KeyInfo keyInfo = new KeyInfo (); KeyInfoX509Data x509KeyInfo = new KeyInfoX509Data (); x509KeyInfo.AddCertificate (new X509Certificate2 (_cert)); x509KeyInfo.AddCertificate (cert); keyInfo.AddClause (x509KeyInfo); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature (); XmlElement xmlDigitalSignature = signedXml.GetXml (); doc.DocumentElement.AppendChild (doc.ImportNode (xmlDigitalSignature, true)); return doc; }
public void DigestValue_LF () { XmlDocument doc = CreateSomeXml ("\n"); XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform (); transform.LoadInput (doc); Stream s = (Stream) transform.GetOutput (); string output = Stream2String (s); Assert.AreEqual ("<person>\n <birthplace>Brussels</birthplace>\n</person>", output, "#1"); s.Position = 0; HashAlgorithm hash = HashAlgorithm.Create ("System.Security.Cryptography.SHA1CryptoServiceProvider"); byte[] digest = hash.ComputeHash (s); Assert.AreEqual ("e3dsi1xK8FAx1vsug7J203JbEAU=", Convert.ToBase64String (digest), "#2"); X509Certificate2 cert = new X509Certificate2 (_pkcs12, "mono"); SignedXml signedXml = new SignedXml (doc); signedXml.SigningKey = cert.PrivateKey; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; Reference reference = new Reference (); reference.Uri = ""; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform (); reference.AddTransform (env); signedXml.AddReference (reference); KeyInfo keyInfo = new KeyInfo (); KeyInfoX509Data x509KeyInfo = new KeyInfoX509Data (); x509KeyInfo.AddCertificate (new X509Certificate2 (_cert)); x509KeyInfo.AddCertificate (cert); keyInfo.AddClause (x509KeyInfo); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature (); digest = reference.DigestValue; Assert.AreEqual ("e3dsi1xK8FAx1vsug7J203JbEAU=", Convert.ToBase64String (digest), "#3"); Assert.AreEqual ("<SignedInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" + "<CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\" />" + "<SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\" />" + "<Reference URI=\"\">" + "<Transforms>" + "<Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\" />" + "</Transforms>" + "<DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\" />" + "<DigestValue>e3dsi1xK8FAx1vsug7J203JbEAU=</DigestValue>" + "</Reference>" + "</SignedInfo>", signedXml.SignedInfo.GetXml ().OuterXml, "#4"); }
public void ComputeSignatureMissingReferencedObject () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<foo/>"); SignedXml signedXml = new SignedXml (doc); DSA key = DSA.Create (); signedXml.SigningKey = key; Reference reference = new Reference (); reference.Uri = "#bleh"; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform (); reference.AddTransform (env); signedXml.AddReference (reference); signedXml.ComputeSignature (); }
public void ComputeSignatureNoSigningKey () { XmlDocument doc = new XmlDocument (); doc.LoadXml ("<foo/>"); SignedXml signedXml = new SignedXml (doc); Reference reference = new Reference (); reference.Uri = ""; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform (); reference.AddTransform (env); signedXml.AddReference (reference); signedXml.ComputeSignature (); }
/// <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.PrivateKey; 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); }
public static SignatureType GeraAssinatura(XmlDocument doc, string pUri, X509Certificate2 cert) { try { var signature = doc.GetElementsByTagName("Signature"); if (signature.Count == 1) { signature.Item(0).ParentNode.RemoveChild(signature.Item(0)); } else if (signature.Count > 1) { throw new InvalidOperationException("Não é possível assinar um documento com mais de uma assinatura existente."); } // Create a SignedXml object. var signedXml = new SignedXml(doc) {SigningKey = cert.PrivateKey}; // Create a reference to be signed. var reference = new Reference(); // pega o uri que deve ser assinada var 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. var env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); var c14 = new XmlDsigC14NTransform(); reference.AddTransform(c14); // Add the reference to the SignedXml object. signedXml.AddReference(reference); // Create a new KeyInfo object. var 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(); var xml = signedXml.GetXml(); using (var sw = new StringWriter()) using (var xw = new XmlTextWriter(sw)) { xml.WriteTo(xw); xw.Close(); var sigXml = sw.ToString(); return SignatureType.Deserialize(sigXml); } } catch (Exception ex) { throw new Exception("Erro ao efetuar assinatura digital, detalhes: " + ex.Message); } }
public static void SignXml(ref XmlDocument document, X509Certificate2 certificate, RequestType requestType) { document.PreserveWhitespace = true; if (requestType == RequestType.Invoice || requestType == RequestType.Buisness_premise) { XmlNode nodeTaxNumber = document.GetElementsByTagName("fu:TaxNumber")[0]; nodeTaxNumber.InnerText = AppLink.VATNumber; string taxNumber = nodeTaxNumber.InnerText; if (requestType == RequestType.Invoice) { string issueDate = DateTime.Now.ToUniversalTime().ToString("s"); XmlNode nodeIssueDate = document.GetElementsByTagName("fu:IssueDateTime")[0]; nodeIssueDate.InnerText = issueDate; XmlNode nodeInvoiceNumber = document.GetElementsByTagName("fu:InvoiceNumber")[0]; string invoiceNumber = nodeInvoiceNumber.InnerText; XmlNode nodeBusinessPremiseID = document.GetElementsByTagName("fu:BusinessPremiseID")[0]; string businessPremiseID = nodeBusinessPremiseID.InnerText; XmlNode nodeElectronicDeviceID = document.GetElementsByTagName("fu:ElectronicDeviceID")[0]; string electronicDeviceID = nodeElectronicDeviceID.InnerText; XmlNode nodeInvoiceAmount = document.GetElementsByTagName("fu:InvoiceAmount")[0]; string invoiceAmount = nodeInvoiceAmount.InnerText; string zoi = CalculateZOI(taxNumber, issueDate, invoiceNumber, businessPremiseID, electronicDeviceID, invoiceAmount, certificate); XmlNode nodeZoi = document.GetElementsByTagName("fu:ProtectedID")[0]; nodeZoi.InnerText = zoi; } } CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); if (document == null) throw new ArgumentException("xmlDoc"); // Create a SignedXml object. SignedXml signedXml = new SignedXml(document); byte[] data = certificate.GetPublicKey(); string base64 = Convert.ToBase64String(data); RSACryptoServiceProvider rsaCSP = (RSACryptoServiceProvider)certificate.PrivateKey; CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = rsaCSP.CspKeyContainerInfo.KeyContainerName; cspParameters.KeyNumber = rsaCSP.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2; RSACryptoServiceProvider rsaAesCSP = new RSACryptoServiceProvider(cspParameters); signedXml.SigningKey = rsaAesCSP; //newKey; KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(); keyInfoData.AddIssuerSerial(certificate.Issuer, certificate.SerialNumber); X509Extension extension = certificate.Extensions[1]; AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData); keyInfoData.AddSubjectName(certificate.SubjectName.Name); // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = "#test"; 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); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); XmlNode element; if (requestType == RequestType.Invoice) { element = document.GetElementsByTagName("fu:InvoiceRequest")[0]; } else { element = document.GetElementsByTagName("fu:BusinessPremiseRequest")[0]; } element.AppendChild(xmlDigitalSignature); }
private static void AssinaXml(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 = "" }; var env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); signedXml.ComputeSignature(); var xmlDigitalSignature = signedXml.GetXml(); if (xmlDoc.DocumentElement != null) { xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); } }
/// <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); }