private SignedXml GetXmlSignature(XmlDocument document, X509Certificate2 certificate, Guid requestId) { LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.DeliveryMailbox.Signing.Handler.SignXmlDocumentHandler: incoming GetXmlSignature with RequestId: {0}", requestId)); SignedXml signedXml = new SignedXml(document); signedXml.SigningKey = certificate.PrivateKey; // Retrieve the value of the "ID" attribute on the root assertion element. Reference reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(reference); signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; // Include the public key of the certificate in the assertion. signedXml.KeyInfo = new KeyInfo(); var keyInfoData = new KeyInfoX509Data(); keyInfoData.AddSubjectName(certificate.SubjectName.Name); keyInfoData.AddCertificate(certificate); signedXml.KeyInfo.AddClause(keyInfoData); signedXml.ComputeSignature(); LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.DeliveryMailbox.Signing.Handler.SignXmlDocumentHandler: leaving GetXmlSignature with RequestId: {0}", requestId)); return(signedXml); }
private KeyInfo GetKeyInfo() { KeyInfo info = null; if (_keyInfoClauses.Count > 0) { info = new KeyInfo(); KeyInfoX509Data clause = new KeyInfoX509Data(); foreach (var item in _keyInfoClauses) { switch (item) { case "RSAKeyValue": RSACryptoServiceProvider pKey = (RSACryptoServiceProvider)_cert.PublicKey.Key; info.AddClause(new RSAKeyValue((RSA)pKey)); break; case "X509IssuerSerial": clause.AddIssuerSerial(_cert.IssuerName.Name, _cert.SerialNumber); break; case "X509SubjectName": clause.AddSubjectName(_cert.SubjectName.Name); break; case "X509Certificate": clause.AddCertificate(_cert); break; } } info.AddClause(clause); } return(info); }
private KeyInfo createKeyInfo(CertificateX509 certificate, string keyInfoType) { KeyInfo keyInfo = new KeyInfo(); KeyInfoType kinfo = KeyInfoTypeUtils.getKeyInfoType(keyInfoType, this.error); switch (kinfo) { case KeyInfoType.KeyValue: if (SecurityUtils.compareStrings(certificate.getPublicKeyAlgorithm(), "RSA")) { keyInfo.AddClause(new RSAKeyValue((RSA)certificate.getPublicKeyXML())); } else { keyInfo.AddClause(new DSAKeyValue((DSA)certificate.getPublicKeyXML())); } break; case KeyInfoType.X509Certificate: KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(); keyInfoX509Data.AddCertificate((X509Certificate)certificate.Cert); keyInfoX509Data.AddSubjectName(certificate.Cert.SubjectName.Name); keyInfoX509Data.AddIssuerSerial(certificate.Cert.IssuerName.Name, certificate.Cert.SerialNumber); keyInfo.AddClause((KeyInfoClause)keyInfoX509Data); break; case KeyInfoType.NONE: keyInfo = null; break; } return(keyInfo); }
/// <summary> /// Signs xmldocument /// </summary> /// <param name="xmlDoc">Document to sign</param> /// <param name="tagName">Element to insert signature after</param> public void SignXmlDocument(XmlDocument xmlDoc, string tagName, X509Certificate2 x509Certificate2 = null) { if (x509Certificate2 != null) { this.x509Certificate2 = x509Certificate2; } xmlDoc.Normalize(); SignedXml signedXml = new SignedXml(xmlDoc); signedXml.SigningKey = this.x509Certificate2.PrivateKey; // Create a reference to be signed. Reference reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(reference); // Specify a canonicalization method. signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; signedXml.KeyInfo = new KeyInfo(); var keyInfoData = new KeyInfoX509Data(); keyInfoData.AddSubjectName(this.x509Certificate2.SubjectName.Name); keyInfoData.AddCertificate(this.x509Certificate2); signedXml.KeyInfo.AddClause(keyInfoData); signedXml.ComputeSignature(); XmlNodeList nodes = xmlDoc.DocumentElement.GetElementsByTagName(tagName); nodes[0].ParentNode.InsertAfter(xmlDoc.ImportNode(signedXml.GetXml(), true), nodes[0]); }
static void Test6() //Xml roundtrip { int i = 0; data = new KeyInfoX509Data(); //add certs data.AddCertificate(TestCert); data.AddCertificate(EndCert); //add subject name data.AddSubjectName(TestCert.SubjectName.Name); data.AddSubjectName(EndCert.SubjectName.Name); //add subject keys data.AddSubjectKeyId(new byte[] { 1, 2, 3, 4, 5, 6 }); data.AddSubjectKeyId(new byte[] { 7, 8, 9, 10, 11, 12 }); //add issuer serials data.AddIssuerSerial(TestCert.IssuerName.Name, TestCert.SerialNumber); data.AddIssuerSerial(EndCert.IssuerName.Name, EndCert.SerialNumber); //add the crl byte[] b = { 100, 101, 102, 104 }; data.CRL = b; KeyInfoX509Data rt = new KeyInfoX509Data(); rt.LoadXml(data.GetXml()); for (i = 0; i < rt.CRL.Length; i++) { rv = rt.CRL[i] == data.CRL[i]; } for (i = 0; i < rt.Certificates.Count; i++) { rv = rt.Certificates[i].ToString() == data.Certificates[i].ToString(); } for (i = 0; i < rt.SubjectKeyIds.Count; i++) { rv = rt.SubjectKeyIds[i].ToString() == data.SubjectKeyIds[i].ToString(); } for (i = 0; i < rt.SubjectNames.Count; i++) { rv = rt.SubjectNames[i].ToString() == data.SubjectNames[i].ToString(); } }
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)); }
public void WriteContentsTo( AddressingVersion addressingVersion, XmlDictionaryWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } #if NET_2_1 writer.WriteString(Uri.AbsoluteUri); #else if (addressingVersion == AddressingVersion.None) { writer.WriteString(Uri.AbsoluteUri); } else { writer.WriteStartElement("Address", addressingVersion.Namespace); writer.WriteString(Uri.AbsoluteUri); writer.WriteEndElement(); if (Identity == null) { return; } if (Headers != null) { foreach (AddressHeader ah in Headers) { ah.WriteAddressHeader(writer); } } writer.WriteStartElement("Identity", Constants.WsaIdentityUri); X509CertificateEndpointIdentity x509 = Identity as X509CertificateEndpointIdentity; if (x509 != null) { KeyInfo ki = new KeyInfo(); KeyInfoX509Data x = new KeyInfoX509Data(); foreach (X509Certificate2 cert in x509.Certificates) { x.AddCertificate(cert); } ki.AddClause(x); ki.GetXml().WriteTo(writer); } else { DataContractSerializer ds = new DataContractSerializer(Identity.IdentityClaim.GetType()); ds.WriteObject(writer, Identity.IdentityClaim); } writer.WriteEndElement(); } #endif }
private static KeyInfo getKeyInfo(X509Certificate certificate) { var keyInfo = new KeyInfo(); var x509Data = new KeyInfoX509Data(); x509Data.AddCertificate(certificate); keyInfo.AddClause(x509Data); return(keyInfo); }
private KeyInfo GetKeyInfo(X509Certificate2 certificate) { KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(); keyInfoData.AddCertificate(certificate); keyInfo.AddClause(keyInfoData); return(keyInfo); }
/// <summary> /// Initializes a new instance of the <see cref="Saml20MetadataDocument"/> class. /// </summary> /// <param name="config">The config.</param> /// <param name="cert">The certificate for Service Provider</param> /// <param name="sign">if set to <c>true</c> the metadata document will be signed.</param> public Saml20MetadataDocument(Saml2Configuration config, X509Certificate2 cert, bool sign = false) : this(sign) { KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(); keyInfoData.AddCertificate(cert); keyInfo.AddClause(keyInfoData); ConvertToMetadata(config, keyInfo); }
private static XmlDocument Sign(XmlDocument doc, RacunZahtjev request) { SignedXml xml = null; xml = new SignedXml(doc); xml.SigningKey = cert.PrivateKey; xml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; xml.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; var keyInfo = new KeyInfo(); var keyInfoData = new KeyInfoX509Data(); keyInfoData.AddCertificate(cert); keyInfoData.AddIssuerSerial(cert.Issuer, cert.GetSerialNumberString()); keyInfo.AddClause(keyInfoData); xml.KeyInfo = keyInfo; var transforms = new Transform[] { new XmlDsigEnvelopedSignatureTransform(false), new XmlDsigExcC14NTransform(false) }; Reference reference = new Reference("#" + request.Id); foreach (var x in transforms) { reference.AddTransform(x); } reference.DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1"; xml.AddReference(reference); xml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = xml.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("SignedXML.xml", new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); return(doc); }
public string Sign(string xmlDocument, RSA rsaKey) { CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); var xml = new XmlDocument { PreserveWhitespace = true }; xml.LoadXml(xmlDocument); if (xml.DocumentElement == null) { throw new CryptographicException($"The xml you are trying to Sign is invalid. \n {xmlDocument}"); } var signedXml = new SignedXml(xml) { SigningKey = rsaKey }; //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; var dataObject = new DataObject(Guid.NewGuid().ToString(), "", "", xml.DocumentElement); signedXml.AddObject(dataObject); var x509Data = new KeyInfoX509Data(); var x509Certificate2 = new X509Certificate2("NPPAutomationClient.pem"); if (x509Certificate2.SerialNumber == null) { throw new CryptographicException("The X509Certificate you are trying to use is invalid. The Serial number is null."); } var keyInfo = new KeyInfo(); var keyInfoX509Data = new KeyInfoX509Data(); keyInfoX509Data.AddIssuerSerial(x509Certificate2.Issuer, x509Certificate2.SerialNumber); keyInfoX509Data.AddCertificate(x509Certificate2); keyInfo.AddClause(keyInfoX509Data); keyInfo.LoadXml(x509Data.GetXml()); var reference = new Reference { Uri = $"#{dataObject.Id}", DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256" }; var env = new XmlDsigC14NTransform(); reference.AddTransform(env); signedXml.AddReference(reference); signedXml.ComputeSignature(); var xmlDigitalSignature = signedXml.GetXml(); //xml.DocumentElement?.AppendChild(xml.ImportNode(xmlDigitalSignature, true)); return(xml.ImportNode(xmlDigitalSignature, true).OuterXml); }
// Creates a KeyInfo from the supplied X.509 certificate private static KeyInfo CreateKeyInfo(X509Certificate2 x509Certificate) { KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(); keyInfoX509Data.AddCertificate(x509Certificate); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(keyInfoX509Data); return(keyInfo); }
/// <summary>Potpisuje XML dokument sanim certifikatom</summary> /// <param name="certificate">Certifikat kojim se potpisuje</param> /// <param name="xmlDocument">XML dokument koji se potpisuje</param> /// <returns>Potpisani XMl dokument</returns> /// <exception cref="ArgumentNullException">Ulazni parametar nije zadan</exception> /// <exception cref="ArgumentException">Elementi ulaznog parametra nisu zadani</exception> /// <exception cref="ApplicationException">Greška u procesu potpisivanja</exception> public static XmlDocument SignXmlDocument(X509Certificate2 certificate, XmlDocument xmlDocument) { #region Input parameter testing if (certificate == null) { throw new ArgumentNullException("certificate", "Method: Helper.SignXmlDocument Parameter: certificate"); } if (xmlDocument == null) { throw new ArgumentNullException("xmlDocument", "Method: Helper.SignXmlDocument Parameter: xmlDocument"); } if (string.IsNullOrEmpty(xmlDocument.InnerXml) || xmlDocument.DocumentElement == null) { throw new ArgumentException("Method: Helper.SignXmlDocument Parameter: xmlDocument Error: InnerXml is null or empty, or DocumentElement is null"); } #endregion try { var signedXml = new SignedXml(xmlDocument); signedXml.SigningKey = certificate.PrivateKey; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; var keyInfoData = new KeyInfoX509Data(); keyInfoData.AddCertificate(certificate); keyInfoData.AddIssuerSerial(certificate.Issuer, certificate.GetSerialNumberString()); var keyInfo = new KeyInfo(); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; var reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(false)); reference.AddTransform(new XmlDsigExcC14NTransform(false)); reference.Uri = "#signXmlId"; signedXml.AddReference(reference); signedXml.ComputeSignature(); var xmlElement = signedXml.GetXml(); xmlDocument.DocumentElement.AppendChild(xmlElement); return(xmlDocument); } catch (Exception ex) { throw new ApplicationException("Method: Helper.SignXmlDocument Error: An error occured during the signing process. See inner exception for details", ex); } }
public void Complex() { KeyInfoX509Data data1 = new KeyInfoX509Data(cert); KeyInfoX509Data data2 = new KeyInfoX509Data(); XmlElement xel = data1.GetXml(); data2.LoadXml(xel); Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml)); byte[] c = (data1.Certificates[0] as X509Certificate).GetRawCertData(); AssertCrypto.AssertEquals("Certificate[0]", cert, c); // add a second X.509 certificate X509Certificate x509 = new X509Certificate(cert2); data1.AddCertificate(x509); xel = data1.GetXml(); data2.LoadXml(xel); Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml)); c = (data1.Certificates[1] as X509Certificate).GetRawCertData(); Assert.Equal(cert2, c); // add properties from a third X.509 certificate x509 = new X509Certificate(cert3); data1.AddIssuerSerial(x509.Issuer, x509.GetSerialNumberString()); xel = data1.GetXml(); data2.LoadXml(xel); Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml)); // TODO: The type of IssuerSerial isn't documented // X509Certificate doesn't export SubjectKeyId so we must improvise byte[] skid = { 0xDE, 0xAD, 0xC0, 0xDE }; data1.AddSubjectKeyId(skid); xel = data1.GetXml(); data2.LoadXml(xel); Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml)); Assert.Equal(skid, (byte[])data1.SubjectKeyIds[0]); data1.AddSubjectName(x509.Subject); xel = data1.GetXml(); data2.LoadXml(xel); Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml)); string s = (string)data1.SubjectNames[0]; Assert.Equal(x509.Subject, s); }
void IXmlSerializable.WriteXml(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } writer.WriteStartElement("Address", Constants.WsaNamespace); writer.WriteString(address.Uri.AbsoluteUri); writer.WriteEndElement(); if (address.Identity == null) { return; } if (address.Headers != null) { foreach (AddressHeader ah in address.Headers) { ah.WriteAddressHeader(writer); } } writer.WriteStartElement("Identity", Constants.WsaIdentityUri); #if !NET_2_1 X509CertificateEndpointIdentity x509 = address.Identity as X509CertificateEndpointIdentity; if (x509 != null) { KeyInfo ki = new KeyInfo(); KeyInfoX509Data x = new KeyInfoX509Data(); foreach (X509Certificate2 cert in x509.Certificates) { x.AddCertificate(cert); } ki.AddClause(x); ki.GetXml().WriteTo(writer); } else { DataContractSerializer ds = new DataContractSerializer(address.Identity.IdentityClaim.GetType()); ds.WriteObject(writer, address.Identity.IdentityClaim); } #endif writer.WriteEndElement(); }
public void Complex() { KeyInfoX509Data data1 = new KeyInfoX509Data(cert); KeyInfoX509Data data2 = new KeyInfoX509Data(); XmlElement xel = data1.GetXml(); data2.LoadXml(xel); Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml)); byte[] c = (data1.Certificates[0] as X509Certificate).GetEncoded(); AssertCrypto.AssertEquals("Certificate[0]", cert, c); X509Certificate x509 = new X509CertificateParser().ReadCertificate(cert2); data1.AddCertificate(x509); xel = data1.GetXml(); data2.LoadXml(xel); Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml)); c = (data1.Certificates[1] as X509Certificate).GetEncoded(); Assert.Equal(cert2, c); x509 = new X509CertificateParser().ReadCertificate(cert3); data1.AddIssuerSerial(x509.IssuerDN.ToString(), x509.SerialNumber.ToString()); xel = data1.GetXml(); data2.LoadXml(xel); Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml)); byte[] skid = { 0xDE, 0xAD, 0xC0, 0xDE }; data1.AddSubjectKeyId(skid); xel = data1.GetXml(); data2.LoadXml(xel); Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml)); Assert.Equal(skid, (byte[])data1.SubjectKeyIds[0]); data1.AddSubjectName(x509.SubjectDN.ToString()); xel = data1.GetXml(); data2.LoadXml(xel); Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml)); string s = (string)data1.SubjectNames[0]; Assert.Equal(x509.SubjectDN.ToString(), s); }
/// <summary> /// Signs a list of references using a certificate and returns /// the signature element. /// </summary> /// <param name="xmlDoc">Xml document that contains the references. /// Cannot be null.</param> /// <param name="signCert">Certificate used for signing that contains a /// private key. The certificate and contained private key cannot be null.</param> /// <param name="references">List of references to sign. Cannot be null.</param> /// <returns>'ds:Signature' element</returns> public static XmlElement Sign(XmlDocument xmlDoc, X509Certificate2 signCert, IList <string> references) { // Create the signature object using the document as the context SignedXml signedXml = new SignedXml(xmlDoc); signedXml.SigningKey = signCert.PrivateKey; // Specify the canonicalization method signedXml.Signature.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; // Specify the signature method signedXml.Signature.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url; // Add all the signing references foreach (string signReferenceId in references) { Reference reference = new Reference(); reference.Uri = "#" + signReferenceId; reference.DigestMethod = SignedXml.XmlDsigSHA1Url; // Add the reference transform XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform(); reference.AddTransform(transform); // Add the reference to the signature signedXml.AddReference(reference); } // Calculate the signature signedXml.ComputeSignature(); // Add the key information to the signature KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data kixd = new KeyInfoX509Data(); kixd.AddCertificate(signCert); keyInfo.AddClause(kixd); signedXml.KeyInfo = keyInfo; // Return the signature return(signedXml.GetXml()); }
private void SignXmlWithP12() { //var privateKey = this.cert.PrivateKey; // Export private key from cert.PrivateKey and import into a PROV_RSA_AES provider: var exportedKeyMaterial = cert.PrivateKey.ToXmlString(/* includePrivateParameters = */ true); var key = new RSACryptoServiceProvider(new CspParameters(24 /* PROV_RSA_AES */)); key.PersistKeyInCsp = false; key.FromXmlString(exportedKeyMaterial); //Create SignedXml object var xmlSigned = new SignedXml(this.xmlDocument); xmlSigned.SigningKey = key; xmlSigned.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; //Create a reference of the document to be signed var reference = new Reference(); reference.Uri = "";//This references the whole document var env = new XmlDsigEnvelopedSignatureTransform(true); reference.AddTransform(env); xmlSigned.AddReference(reference); //Set KeyInfo var keyInfo = new KeyInfo(); var clause = new KeyInfoX509Data(); //clause.AddSubjectName(cert.Subject); clause.AddCertificate(cert); keyInfo.AddClause(clause); //Assign the KeyInfo the SignedXml object xmlSigned.KeyInfo = keyInfo; xmlSigned.ComputeSignature(); XmlElement xmlDigitalSignature = xmlSigned.GetXml(); //Append the signature to this xml document this.xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(xmlDigitalSignature, true)); }
private void AddCertificateInfoToSignature(XadesSignedXml xadesSignedXml, SignatureParameters parameters) { var key = parameters.SigningCertificate.GetPublicKey(); if (key is RsaKeyParameters) { RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(); RSAParameters RSAKeyInfo = new RSAParameters(); //Set RSAKeyInfo to the public key values. RSAKeyInfo.Modulus = ((RsaKeyParameters)key).Modulus.ToByteArray(); RSAKeyInfo.Exponent = ((RsaKeyParameters)key).Exponent.ToByteArray(); rsaKey.ImportParameters(RSAKeyInfo); xadesSignedXml.SigningKey = rsaKey; KeyInfo keyInfo = new KeyInfo(); // ETSI TS 103 171 V2.1.1 // 6.2.1 Placement of the signing certificate // "b) In order to facilitate path-building, generators should include in the same ds:KeyInfo/X509Data element as // in note a) all certificates not available to verifiers that can be used during path building." //keyInfo.AddClause(new KeyInfoX509Data(this.certificate)); { KeyInfoX509Data x509Data = new KeyInfoX509Data(); foreach (X509Certificate cert in parameters.CertificateChain) { x509Data.AddCertificate(DotNetUtilities.ToX509Certificate2(cert)); //TODO jbonilla validar más de uno? //break; } keyInfo.AddClause(x509Data); } keyInfo.AddClause(new RSAKeyValue(rsaKey)); xadesSignedXml.KeyInfo = keyInfo; } else { throw new ArgumentException("Only allowed RsaKeyParameters", "key"); } }
public static XmlElement Generate(XmlElement xmlElement, string elementId, AsymmetricAlgorithm signingKey, X509Certificate2Collection x509Certificates, SignedXml signedXml, string inclusiveNamespacesPrefixList, string digestMethod, string signatureMethod) { KeyInfo keyInfo; try { keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(); foreach (X509Certificate2 x509Certificate in x509Certificates) { keyInfoX509Data.AddCertificate((X509Certificate)x509Certificate); } keyInfo.AddClause((KeyInfoClause)keyInfoX509Data); } catch (Exception ex) { throw new SamlSignatureException("Failed to create key info using X.509 certificate.", ex); } return(XmlSignature.Generate(xmlElement, elementId, signingKey, keyInfo, signedXml, inclusiveNamespacesPrefixList, digestMethod, signatureMethod)); }
/// <summary> /// Potpisuje XML dokument.</summary> /// <param name="dokument">XML dokument koji treba potpisati.</param> /// <param name="certifikat">Certifikat koji se koristi kod potpisivanja.</param> /// <example> /// PopratneFunkcije.Potpisivanje.PotpisiXmlDokument(zahtjevXml, certificate); /// </example> /// <returns> /// Vraća potpisani XMl dokument.</returns> public static XmlDocument PotpisiXmlDokument(XmlDocument dokument, X509Certificate2 certifikat) { RSACryptoServiceProvider provider = (RSACryptoServiceProvider)certifikat.PrivateKey; SignedXml xml = null; try { xml = new SignedXml(dokument); xml.SigningKey = provider; xml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(); keyInfoData.AddCertificate(certifikat); keyInfoData.AddIssuerSerial(certifikat.Issuer, certifikat.GetSerialNumberString()); keyInfo.AddClause(keyInfoData); xml.KeyInfo = keyInfo; Reference reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(false)); reference.AddTransform(new XmlDsigExcC14NTransform(false)); reference.Uri = "#signXmlId"; xml.AddReference(reference); xml.ComputeSignature(); XmlElement element = xml.GetXml(); dokument.DocumentElement.AppendChild(element); } catch (Exception ex) { Trace.TraceError(String.Format("Greška kod potpisivanja XML dokumenta: {0}", ex.Message)); throw; } return(dokument); }
/// <summary> /// Signs an XmlDocument with an xml signature. /// </summary> public XmlDocument SignXmlDocument(XmlDocument document, X509Certificate2 certificate, Guid requestId) { LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.Signing.Handler.SignXmlDocumentHandler: incoming SignXmlDocument with RequestId: {0}", requestId)); document.Normalize(); SignedXml signedXml = new SignedXml(document); signedXml.SigningKey = certificate.PrivateKey; // Retrieve the value of the "ID" attribute on the root assertion element. Reference reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(reference); signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; // Include the public key of the certificate in the assertion. signedXml.KeyInfo = new KeyInfo(); var keyInfoData = new KeyInfoX509Data(); keyInfoData.AddSubjectName(certificate.SubjectName.Name); keyInfoData.AddCertificate(certificate); signedXml.KeyInfo.AddClause(keyInfoData); signedXml.ComputeSignature(); // Append the computed signature. The signature must be placed as the sibling of the Issuer element. XmlNodeList nodes = document.DocumentElement.GetElementsByTagName("Delivery"); nodes[0].ParentNode.InsertAfter(document.ImportNode(signedXml.GetXml(), true), nodes[0]); LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.Signing.Handler.SignXmlDocumentHandler: leaving SignXmlDocument with RequestId: {0}", requestId)); return(document); }
public void AddCertificate_Null() { KeyInfoX509Data data = new KeyInfoX509Data(); data.AddCertificate(null); }
public void AddCertificate_Null() { KeyInfoX509Data data = new KeyInfoX509Data(); Assert.Throws <ArgumentNullException>(() => data.AddCertificate(null)); }
public static void FirmaXML(string RutaXml, string nombrexml) { try { //Declaro variable XMLDocument XmlDocument xmlDoc = new XmlDocument(); // Cargo el documento en el xmlDoc xmlDoc.PreserveWhitespace = true; //var PathServer = ConfigurationManager.AppSettings["XmlServidor"]; var PathServer = @"C:\Users\Public\Documents\ArchivosXml"; string pathXml = PathServer + @"\sonna_judith_vega_solis.p12"; xmlDoc.Load(@RutaXml); //string soapSecNS = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; //Obtengo la firma en el Certificado X509 X509Certificate2 uidCert = new X509Certificate2(pathXml, "Sonnav67", X509KeyStorageFlags.DefaultKeySet); //string nombre = uidCert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.DnsName,true); //Console.WriteLine(nombre); //Inicializo el RSA RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)uidCert.PrivateKey; //Agrego el SgnedXml que permite firmar el xml SignedXml signedXml = new SignedXml(xmlDoc); // Add the key to the SignedXml document. signedXml.SigningKey = rsaKey; signedXml.Signature.Id = newID("Signature"); //Agregamos el metodo de firmado signedXml.SignedInfo.SignatureMethod = XmlDsigRSASHA1Url; signedXml.SignedInfo.Id = newID("Signature-SignedInfo"); // Create a reference to be signed. Reference reference = new Reference(); //reference.Id = newID("#Certificate"); 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); keyInfo.Id = newID("Certificate1"); signedXml.KeyInfo = keyInfo; // Compute the signature. signedXml.ComputeSignature(); Boolean respuesta = signedXml.CheckSignature(); System.Console.WriteLine(respuesta); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); //XmlElement signature = signedXml.GetXml(); foreach (XmlNode node in xmlDigitalSignature.SelectNodes( "descendant-or-self::*[namespace-uri()='http://www.w3.org/2000/09/xmldsig#']")) { node.Prefix = "ds"; } System.Console.WriteLine(signedXml.GetXml().InnerXml); // Append the element to the XML document. xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); //Preguntar sobre el directorio if (!Directory.Exists(PathServer + @"\Firmados\")) { Directory.CreateDirectory(PathServer + @"\Firmados\"); } xmlDoc.Save(@PathServer + @"\Firmados\" + @"\" + nombrexml + ".xml"); } catch (Exception e) { Console.WriteLine(e.Message); } finally { System.Console.ReadLine(); } }
static void Test6() //Xml roundtrip { int i = 0 ; data = new KeyInfoX509Data() ; //add certs data.AddCertificate( TestCert ) ; data.AddCertificate( EndCert ) ; //add subject name data.AddSubjectName( TestCert.SubjectName.Name ) ; data.AddSubjectName( EndCert.SubjectName.Name ) ; //add subject keys data.AddSubjectKeyId( new byte[]{1,2,3,4,5,6} ) ; data.AddSubjectKeyId( new byte[]{7,8,9,10,11,12} ) ; //add issuer serials data.AddIssuerSerial( TestCert.IssuerName.Name , TestCert.SerialNumber ) ; data.AddIssuerSerial( EndCert.IssuerName.Name , EndCert.SerialNumber ) ; //add the crl byte[] b = { 100, 101 , 102 , 104 } ; data.CRL = b ; KeyInfoX509Data rt = new KeyInfoX509Data() ; rt.LoadXml( data.GetXml() ) ; for( i = 0 ; i < rt.CRL.Length ; i++ ) { rv = rt.CRL[i] == data.CRL[i] ; } for( i = 0 ; i < rt.Certificates.Count ; i++ ) { rv = rt.Certificates[i].ToString() == data.Certificates[i].ToString() ; } for( i = 0 ; i < rt.SubjectKeyIds.Count ; i++ ) { rv = rt.SubjectKeyIds[i].ToString() == data.SubjectKeyIds[i].ToString() ; } for( i = 0 ; i < rt.SubjectNames.Count ; i++ ) { rv = rt.SubjectNames[i].ToString() == data.SubjectNames[i].ToString() ; } }
public static void SignRequest(object request, X509Certificate2 certificate) { XmlDocument requestXml = ConvertToXml(request); SignedXml xml = new SignedXml(requestXml); xml.SigningKey = certificate.GetRSAPrivateKey(); xml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; xml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; xml.KeyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(); keyInfoData.AddCertificate(certificate); xml.KeyInfo.AddClause(keyInfoData); Reference reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(false)); reference.AddTransform(new XmlDsigExcC14NTransform(false)); reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; reference.Uri = "#Request"; xml.AddReference(reference); xml.ComputeSignature(); var signature = new SignatureType { SignedInfo = new SignedInfoType { CanonicalizationMethod = new CanonicalizationMethodType { Algorithm = SignedXml.XmlDsigExcC14NTransformUrl }, SignatureMethod = new SignatureMethodType { Algorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" }, Reference = new ReferenceType[] { new ReferenceType { URI = "#Request", Transforms = new TransformType[] { new TransformType { Algorithm = "http://www.w3.org/2000/09/xmldsig#enveloped-signature" }, new TransformType { Algorithm = "http://www.w3.org/2001/10/xml-exc-c14n#" }, }, DigestMethod = new DigestMethodType { Algorithm = "http://www.w3.org/2001/04/xmlenc#sha256" }, DigestValue = ((Reference)xml.SignedInfo.References[0]).DigestValue } } }, SignatureValue = new SignatureValueType { Value = xml.SignatureValue }, KeyInfo = new KeyInfoType { ItemsElementName = new ItemsChoiceType2[] { ItemsChoiceType2.X509Data }, Items = new object[] { new X509DataType { ItemsElementName = new ItemsChoiceType[] { ItemsChoiceType.X509Certificate, ItemsChoiceType.X509SubjectName }, Items = new object[] { certificate.RawData, certificate.SubjectName.Name } } } } }; var property = request.GetType().GetProperty("Signature"); property.SetValue(request, signature, null); }
//sourced https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-sign-xml-documents-with-digital-signatures // 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 = secretKeyBundle.Key.ToRSA(); // Check arguments. if (xmlDoc == null) { throw new ArgumentException("xmlDoc"); } if (key == null) { throw new ArgumentException("key"); } // Create a SignedXml object. CustomSignedXml signedXml = new CustomSignedXml(xmlDoc); // Add the key to the SignedXml document. signedXml.SigningKey = key; // add key info KeyInfo importKeyInfo = new KeyInfo(); KeyInfoX509Data importKeyInfoData = new KeyInfoX509Data(); X509Certificate tempCert = new X509Certificate(publicCertBundle.Cer); importKeyInfoData.AddCertificate(tempCert); importKeyInfoData.AddIssuerSerial(tempCert.Issuer, tempCert.GetSerialNumberString()); importKeyInfo.AddClause(importKeyInfoData); signedXml.KeyInfo = importKeyInfo; // 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)); xmlDoc.Save(XMLFileOutputName); var test = Verify(xmlDoc); Console.WriteLine("XML Signed and validated as: " + test.ToString()); }