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; }
public static string Sign(string xml, X509Certificate2 certificate) { if (xml == null) throw new ArgumentNullException("xml"); if (certificate == null) throw new ArgumentNullException("certificate"); if (!certificate.HasPrivateKey) throw new ArgumentException("certificate", "Certificate should have a private key"); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); SignedXml signedXml = new SignedXml(doc); signedXml.SigningKey = certificate.PrivateKey; // Attach certificate KeyInfo KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; // Attach transforms var reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(includeComments: false)); reference.AddTransform(new XmlDsigExcC14NTransform(includeComments: false)); signedXml.AddReference(reference); // Compute signature signedXml.ComputeSignature(); var signatureElement = signedXml.GetXml(); // Add signature to bundle doc.DocumentElement.AppendChild(doc.ImportNode(signatureElement, true)); return doc.OuterXml; }
static SignedXmlHelper() { var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(TestCert)); KeyInfoXml = keyInfo.GetXml().OuterXml; }
/// <summary> /// Creates the necessary key descriptors for the metadata based on the certificate in the IDPConfig class. /// </summary> /// <returns></returns> private static KeyDescriptor[] CreateKeyDescriptors() { List<KeyDescriptor> keys = new List<KeyDescriptor>(); // Pack the certificate. KeyInfo keyinfo = new KeyInfo(); KeyInfoX509Data keyClause = new KeyInfoX509Data(IDPConfig.IDPCertificate, X509IncludeOption.EndCertOnly); keyinfo.AddClause(keyClause); { // Create signing key element. KeyDescriptor key = new KeyDescriptor(); keys.Add(key); key.use = KeyTypes.signing; key.useSpecified = true; key.KeyInfo = Serialization.DeserializeFromXmlString<dk.nita.saml20.Schema.XmlDSig.KeyInfo>(keyinfo.GetXml().OuterXml); } { // Create encryption key element KeyDescriptor key = new KeyDescriptor(); keys.Add(key); key.use = KeyTypes.encryption; key.useSpecified = true; key.KeyInfo = Serialization.DeserializeFromXmlString<dk.nita.saml20.Schema.XmlDSig.KeyInfo>(keyinfo.GetXml().OuterXml); } return keys.ToArray(); }
private KeyInfoClause CreateEncryptedKeyClause(byte[] key, X509Certificate2 certificate, XmlDocument document) { var keyInfo = new KeyInfo(); keyInfo.AddClause(CreateKeyInfoClause(certificate, document, out _)); return(CreateEncryptedKeyClause(key, keyInfo)); }
private KeyInfoClause CreateEncryptedKeyClause(byte[] key, RSA rsa, XmlDocument document) { var keyInfo = new KeyInfo(); keyInfo.AddClause(CreateKeyInfoClause(rsa)); return(CreateEncryptedKeyClause(key, keyInfo)); }
private static XmlDocument SignXmlDocument(XmlDocument xmlDocument, X509Certificate2 signingCertificate) { // Создание подписчика XML-документа var signedXml = new GostSignedXml(xmlDocument); // Установка ключа для создания подписи signedXml.SetSigningCertificate(signingCertificate); // Ссылка на узел, который нужно подписать, с указанием алгоритма хэширования var dataReference = new Reference { Uri = "#Id1", DigestMethod = GostSignedXml.XmlDsigGost3411Url }; // Установка ссылки на узел signedXml.AddReference(dataReference); // Установка информации о сертификате, который использовался для создания подписи var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(signingCertificate)); signedXml.KeyInfo = keyInfo; // Вычисление подписи signedXml.ComputeSignature(); // Получение XML-представления подписи var signatureXml = signedXml.GetXml(); // Добавление подписи в исходный документ xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(signatureXml, true)); return xmlDocument; }
/// <summary> /// Adds a digital signature to the outgoing request message, before sending it to Acquirer. /// </summary> /// <param name="requestXml"> /// The unsigned request XML message. /// </param> /// <returns> /// The request message, including digital signature. /// </returns> public string SignRequestXml(XDocument requestXml) { XmlDocument document = ToXmlDocument(requestXml); RSACryptoServiceProvider key = ExtractPrivateKeyFrom(acceptantPrivateCertificate); var signedXml = new SignedXml(document) { SigningKey = key }; signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#"; // Add a signing reference, the uri is empty and so the whole document is signed. var reference = new Reference { DigestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256" }; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.Uri = ""; signedXml.AddReference(reference); // Add the certificate as key info. Because of this, the certificate // with the public key will be added in the signature part. var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoName(acceptantPrivateCertificate.Thumbprint)); signedXml.KeyInfo = keyInfo; // Generate the signature. signedXml.ComputeSignature(); XmlElement xmlSignature = signedXml.GetXml(); document.DocumentElement.AppendChild(document.ImportNode(xmlSignature, true)); // Check that outgoing signature is valid. Private certificate also contains public part. VerifyDocumentSignature(document, acceptantPrivateCertificate); return GetContentsFrom(document); }
private static XmlDocument SignXml() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(".\\certificates\\samlRequestTemplate.xml"); X509Certificate2 certificate = CertificateHelper.GetCertificate(".\\certificates\\HuaweiCA.p12", "Pr0d1234"); //AsymmetricAlgorithm key = certificate.PrivateKey; AsymmetricAlgorithm key = certificate.PrivateKey; XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable); ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion"); ns.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); XmlElement issuerNode = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("saml:Issuer", ns); SignedXml signedXml = new SignedXml(xmlDoc.DocumentElement); signedXml.SigningKey = key; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; KeyInfo keyInfo = new KeyInfo(); //XmlDocument keyDoc = new XmlDocument(); //keyDoc.LoadXml(certificate.PublicKey.Key.ToXmlString(false)); //keyInfo.LoadXml(keyDoc.DocumentElement); keyInfo.AddClause(new KeyInfoX509Data(certificate)); signedXml.KeyInfo = keyInfo; string refId = xmlDoc.DocumentElement.GetAttribute("ID"); Reference reference = new Reference(); reference.Uri = "#" + refId; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); XmlDsigExcC14NTransform env2 = new XmlDsigExcC14NTransform(); env2.InclusiveNamespacesPrefixList = "#default code ds kind rw saml samlp typens"; reference.AddTransform(env2); signedXml.AddReference(reference); signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDoc.DocumentElement.InsertAfter(xmlDoc.ImportNode(xmlDigitalSignature, true), issuerNode); //xmlDoc.NameTable.Add("samlp"); //XmlElement nameIDPolicyElem = xmlDoc.CreateElement("samlp", "NameIDPolicy", "urn:oasis:names:tc:SAML:2.0:protocol"); //nameIDPolicyElem.SetAttribute("AllowCreate", "False"); //xmlDoc.DocumentElement.AppendChild(nameIDPolicyElem); xmlDoc.Save("samleRequestCSharp.xml"); return xmlDoc; }
/// <summary> /// Obtiene la información de la firma asociada al certificado digital /// </summary> private KeyInfo GetKeyInfoFromCertificate(X509Certificate2 objCertificate) { KeyInfo objKeyInfo = new KeyInfo(); // Añade la cláusula con el certificado objKeyInfo.AddClause(new KeyInfoX509Data(objCertificate)); // Devuelve la información return objKeyInfo; }
/// <summary> /// Raised when the SAML 2.0 response parameter has been detected. /// </summary> /// <param name="url">URL of the page.</param> /// <param name="query">The parsed query of the URL.</param> /// <param name="fragment">The parsed fragment of the URL.</param> /// <param name="formParams">Form parameters, including the 'SAMLResponse'.</param> protected override void OnRedirectPageLoaded(Uri url, System.Collections.Generic.IDictionary <string, string> query, System.Collections.Generic.IDictionary <string, string> fragment, IDictionary <string, string> formParams) { string base64SamlAssertion = formParams.ContainsKey("SAMLResponse") ? formParams ["SAMLResponse"] : string.Empty; byte[] xmlSamlAssertionBytes = Convert.FromBase64String(base64SamlAssertion); string xmlSamlAssertion = System.Text.UTF8Encoding.Default.GetString(xmlSamlAssertionBytes); XmlDocument xDoc = new XmlDocument(); xDoc.PreserveWhitespace = true; xDoc.LoadXml(xmlSamlAssertion); XmlElement responseElement = (XmlElement)xDoc.SelectSingleNode("//*[local-name()='Response']"); #if DEBUG Console.WriteLine("{0}", responseElement.OuterXml); #endif XmlElement assertionElement = (XmlElement)xDoc.SelectSingleNode("//*[local-name()='Assertion']"); if (assertionElement != null) { #if DEBUG Console.WriteLine("{0}", assertionElement.OuterXml); #endif Saml20Assertion samlAssertion = new Saml20Assertion(assertionElement, null, AssertionProfile.Core, false, false); List <AsymmetricAlgorithm> trustedIssuers = new List <AsymmetricAlgorithm>(1); foreach (KeyDescriptor key in _idpMetadata.Keys) { System.Security.Cryptography.Xml.KeyInfo ki = (System.Security.Cryptography.Xml.KeyInfo)key.KeyInfo; foreach (KeyInfoClause clause in ki) { AsymmetricAlgorithm aa = XmlSignatureUtils.ExtractKey(clause); trustedIssuers.Add(aa); } } try { samlAssertion.CheckValid(trustedIssuers); SamlAccount sa = new SamlAccount(samlAssertion, responseElement); OnSucceeded(sa); } catch (Saml20Exception samlEx) { Console.WriteLine(samlEx); OnError(samlEx.Message); } catch (Exception ex) { Console.WriteLine(ex); OnError(ex.Message); } } else { OnError("No SAML Assertion Found");; } }
/// <summary> /// An example on how to decrypt an encrypted assertion. /// </summary> /// <param name="file">The file.</param> public static void DecryptAssertion(string file) { var doc = new XmlDocument(); doc.Load(file); var encryptedDataElement = GetElement(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc, doc); var encryptedData = new EncryptedData(); encryptedData.LoadXml(encryptedDataElement); var nodelist = doc.GetElementsByTagName(Schema.XmlDSig.KeyInfo.ElementName, Saml20Constants.Xmldsig); Assert.That(nodelist.Count > 0); var key = new KeyInfo(); key.LoadXml((XmlElement)nodelist[0]); // Review: Is it possible to figure out which certificate to load based on the Token? /* * Comment: * It would be possible to provide a key/certificate identifier in the EncryptedKey element, which contains the "recipient" attribute. * The implementation (Safewhere.Tokens.Saml20.Saml20EncryptedAssertion) currently just expects an appropriate asymmetric key to be provided, * and is not not concerned about its origin. * If the need arises, we can easily extend the Saml20EncryptedAssertion class with a property that allows extraction key info, eg. the "recipient" * attribute. */ var cert = new X509Certificate2(@"Certificates\sts_dev_certificate.pfx", "test1234"); // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref18/html/T_System_Security_Cryptography_Xml_KeyInfoClause_DerivedTypes.htm // Look through the list of KeyInfo elements to find the encrypted key. SymmetricAlgorithm symmetricKey = null; foreach (KeyInfoClause keyInfoClause in key) { if (keyInfoClause is KeyInfoEncryptedKey) { var keyInfoEncryptedKey = (KeyInfoEncryptedKey)keyInfoClause; var encryptedKey = keyInfoEncryptedKey.EncryptedKey; symmetricKey = new RijndaelManaged { Key = EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)cert.PrivateKey, false) }; } } // Explode if we didn't manage to find a viable key. Assert.IsNotNull(symmetricKey); var encryptedXml = new EncryptedXml(); var plaintext = encryptedXml.DecryptData(encryptedData, symmetricKey); var assertion = new XmlDocument(); assertion.Load(new StringReader(System.Text.Encoding.UTF8.GetString(plaintext))); // A very simple test to ensure that there is indeed an assertion in the plaintext. Assert.AreEqual(Assertion.ElementName, assertion.DocumentElement.LocalName); Assert.AreEqual(Saml20Constants.Assertion, assertion.DocumentElement.NamespaceURI); // At this point, assertion will contain a decrypted assertion. }
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()); } }
protected EncryptedType () { cipherData = new CipherData (); encoding = null; encryptionMethod = null; encryptionProperties = new EncryptionPropertyCollection (); id = null; keyInfo = new KeyInfo (); mimeType = null; type = null; }
/// <summary> /// Creates a KeyInfo object based on information from specified certificate /// </summary> /// <param name="certificate">The certificate used to create the KeyInfo from</param> /// <returns>KeyInfo object</returns> private static KeyInfo CreateKeyInfoFromCertificate(X509Certificate2 certificate) { // create KeyInfoX509Data object & include certificate subject KeyInfoX509Data kiData = new KeyInfoX509Data(certificate); kiData.AddSubjectName(certificate.Subject); // create KeyInfo object with specified KeyInfoX509Data KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(kiData); return keyInfo; }
private XmlElement CreateEncryptedSymmetricKeyInfo(byte[] key, EncryptingCredentials credentials, XmlDocument document) { var digestMethod = null as string; var clause = null as Legacy.KeyInfoClause; if (credentials.Key is X509SecurityKey x509) { digestMethod = "http://www.w3.org/2000/09/xmldsig#sha1"; var securityTokenReference = document.CreateElement(WsSecurityConstants.WsSecurity10.Prefix, "SecurityTokenReference", WsSecurityConstants.WsSecurity10.Namespace); var keyIdentifier = document.CreateElement(WsSecurityConstants.WsSecurity10.Prefix, "KeyIdentifier", WsSecurityConstants.WsSecurity10.Namespace); keyIdentifier.SetAttribute("ValueType", "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1"); keyIdentifier.InnerText = x509.X5t; securityTokenReference.AppendChild(keyIdentifier); using (var rsa = x509.Certificate.GetRSAPublicKey()) clause = EncryptKey(key, rsa, credentials.Alg, new Legacy.KeyInfoNode(securityTokenReference)); } else if (credentials.Key is RsaSecurityKey rsa) { clause = EncryptKey(key, rsa.Rsa, credentials.Alg, CreateKeyInfoClause(rsa)); } else { throw new NotSupportedException($"Encryption key type '{credentials?.Key.GetType()?.Name}' not supported."); } var keyInfo = new Legacy.KeyInfo(); keyInfo.AddClause(clause); var element = keyInfo.GetXml(); if (digestMethod != null) { var encryptionMethods = element .SelectNodes("//*") .OfType <XmlElement>() .Where(e => e.LocalName == "EncryptionMethod") .Where(e => { var algorithm = e.GetAttribute("Algorithm"); return(algorithm == Legacy.EncryptedXml.XmlEncRSAOAEPUrl); }) ; foreach (var encryptionMethod in encryptionMethods) { var digest = element.OwnerDocument.CreateElement("DigestMethod", "http://www.w3.org/2000/09/xmldsig#"); digest.SetAttribute("Algorithm", digestMethod); encryptionMethod.AppendChild(digest); } } return(element); }
private void CreateMetadataDocument(HttpContext context, bool sign) { SAML20FederationConfig configuration = ConfigurationReader.GetConfig<SAML20FederationConfig>(); KeyInfo keyinfo = new KeyInfo(); KeyInfoX509Data keyClause = new KeyInfoX509Data(ConfigurationReader.GetConfig<FederationConfig>().SigningCertificate.GetCertificate(), X509IncludeOption.EndCertOnly); keyinfo.AddClause(keyClause); Saml20MetadataDocument doc = new Saml20MetadataDocument(configuration, keyinfo, sign); context.Response.Write(doc.ToXml( context.Response.ContentEncoding )); }
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; } } } }
private KeyInfo getKeyInfo() { X509Extension extension = this.settings.Certificate.Extensions[1]; AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(); keyInfoData.AddIssuerSerial(this.settings.Certificate.Issuer, this.settings.Certificate.SerialNumber); keyInfoData.AddSubjectName(this.settings.Certificate.SubjectName.Name); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(keyInfoData); return keyInfo; }
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); } }
private void Encrypt() { _encryptedStream.Position = 0; var algorithm = _credentials.Enc; var document = new XmlDocument(); document.Load(_encryptedStream); var symmetric = Crypto.CreateSymmetricAlgorithm(algorithm); var xml = new EncryptedXml(); xml.Mode = symmetric.Mode; var cipherText = xml.EncryptData(document.DocumentElement, symmetric, false); var keyInfo = new KeyInfo(); var data = new EncryptedData { Type = EncryptedXml.XmlEncElementUrl, EncryptionMethod = new EncryptionMethod(algorithm), CipherData = new CipherData { CipherValue = cipherText } }; if (_credentials.Key is RsaSecurityKey rsa) { keyInfo.AddClause(CreateEncryptedKeyClause(symmetric.Key, rsa.Rsa, document)); } else if (_credentials.Key is X509SecurityKey x509) { keyInfo.AddClause(CreateEncryptedKeyClause(symmetric.Key, x509.Certificate, document)); } else if (!string.IsNullOrEmpty(_credentials.Key.KeyId)) { keyInfo.AddClause(new KeyInfoName(_credentials.Key.KeyId)); } if (keyInfo.Cast <KeyInfoClause>().Any()) { data.KeyInfo = keyInfo; } var element = data.GetXml(); //element = AddDigestMethodToEncryptionMethod(element, "http://www.w3.org/2000/09/xmldsig#sha1"); WriteNode(element.CreateNavigator(), true); Crypto.ReleaseSymmetricAlgorithm(symmetric); }
public bool IsValid(KeyInfo keyInfo) { SignedXml xml = new SignedXml(_doc); XmlNodeList nodeList = _doc.GetElementsByTagName("Signature"); xml.LoadXml((XmlElement)nodeList[0]); xml.KeyInfo = keyInfo; xml.Resolver = null; return xml.CheckSignature(); }
public static Signature ObterAssinatura <T>(T objeto, string id, X509Certificate2 certificadoDigital, string signatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1", string digestMethod = "http://www.w3.org/2000/09/xmldsig#sha1") where T : class { if (id == null) { throw new Exception("Não é possível assinar um objeto evento sem sua respectiva Id!"); } var documento = new XmlDocument { PreserveWhitespace = true }; var xml = XmlUtils.ClasseParaXmlString(objeto); documento.LoadXml(xml); var docXml = new SignedXml(documento) { SigningKey = certificadoDigital.PrivateKey }; docXml.SignedInfo.SignatureMethod = signatureMethod; var reference = new Reference { Uri = "#" + id, DigestMethod = digestMethod }; var envelopedSigntature = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(envelopedSigntature); var c14Transform = new XmlDsigC14NTransform(); reference.AddTransform(c14Transform); docXml.AddReference(reference); var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificadoDigital)); docXml.KeyInfo = keyInfo; docXml.ComputeSignature(); var xmlDigitalSignature = docXml.GetXml(); var assinatura = XmlUtils.XmlStringParaClasse <Signature>(xmlDigitalSignature.OuterXml); return(assinatura); }
public static void SignDetachedResource(string inputFile, string outputSignatureXML, string certFile, String certPassword) { X509Certificate2 certxml = new X509Certificate2(certFile, certPassword); RSACryptoServiceProvider Key = (RSACryptoServiceProvider)certxml.PrivateKey; String XmlSigFileName = outputSignatureXML; // Sign the detached resourceand save the signature in an XML file. // Create a SignedXml object. SignedXml signedXml = new SignedXml(); // Assign the key to the SignedXml object. signedXml.SigningKey = Key; // Create a reference to be signed. Reference reference = new Reference(); // Add the passed Refrence to the reference object. reference.Uri = inputFile; // 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)); if (certxml != null) { KeyInfoX509Data kinfox509 = new KeyInfoX509Data(certxml, X509IncludeOption.WholeChain); kinfox509.AddIssuerSerial(certxml.Issuer, certxml.SerialNumber); kinfox509.AddSubjectName(certxml.Subject); keyInfo.AddClause(kinfox509); } 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(); // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(XmlSigFileName, new UTF8Encoding(false)); xmlDigitalSignature.WriteTo(xmltw); xmltw.Close(); }
public static KeyInfo GetKeyInfoFromXml(string xml) { // Use machine key store CspParameters cspParams = new CspParameters(); cspParams.Flags = CspProviderFlags.UseMachineKeyStore; RSA rsa = new RSACryptoServiceProvider(cspParams); rsa.FromXmlString(xml); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue(rsa)); return keyInfo; }
/// <summary> /// Creates the metadata document. /// </summary> /// <param name="context">The context.</param> /// <param name="sign">if set to <c>true</c> sign the document.</param> private void CreateMetadataDocument(HttpContext context, bool sign) { Logger.Debug(TraceMessages.MetadataDocumentBeingCreated); var configuration = Saml2Config.GetConfig(); var keyinfo = new KeyInfo(); var keyClause = new KeyInfoX509Data(Saml2Config.GetConfig().ServiceProvider.SigningCertificate.GetCertificate(), X509IncludeOption.EndCertOnly); keyinfo.AddClause(keyClause); var doc = new Saml20MetadataDocument(configuration, keyinfo, sign); Logger.Debug(TraceMessages.MetadataDocumentCreated); context.Response.Write(doc.ToXml(context.Response.ContentEncoding)); }
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; }
public override string SignXml(XmlDocument Document) { SignedXmlWithId signedXml = new SignedXmlWithId(Document); signedXml.SigningKey = manager.Certificate.PrivateKey; KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(manager.Certificate); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; // the DataObject has to point to a XmlNodeList DataObject dataObject = new DataObject(); dataObject.Id = "MyObjectID1"; dataObject.Data = new CustomXmlNodeList(new[] { Document.DocumentElement }); signedXml.AddObject(dataObject); // Add the reference to the SignedXml object. Reference reference = new Reference(); reference.Uri = "#MyObjectID1"; signedXml.AddReference(reference); // Create a reference to be signed. if (c14) { XmlDsigC14NTransform env = new XmlDsigC14NTransform(); reference.AddTransform(env); } // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); // create detached envelope XmlDocument envelope = new XmlDocument(); envelope.AppendChild(envelope.CreateElement("Envelope")); envelope.DocumentElement.AppendChild( envelope.ImportNode(xmlDigitalSignature, true)); return envelope.OuterXml; }
public override string SignXml(XmlDocument Document) { // create detached envelope XmlDocument envelope = new XmlDocument(); envelope.PreserveWhitespace = true; envelope.AppendChild(envelope.CreateElement("Envelope")); XmlElement message = envelope.CreateElement("Message"); message.InnerXml = Document.DocumentElement.OuterXml; message.SetAttribute("Id", "MyObjectID"); envelope.DocumentElement.AppendChild(message); SignedXmlWithId signedXml = new SignedXmlWithId(envelope); signedXml.SigningKey = manager.Certificate.PrivateKey; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = "#MyObjectID"; if (c14) { XmlDsigC14NTransform env = new XmlDsigC14NTransform(); reference.AddTransform(env); } 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(); envelope.DocumentElement.AppendChild( envelope.ImportNode(xmlDigitalSignature, true)); return envelope.OuterXml; }
public void ComputeSignature(X509Certificate2 certificate, X509IncludeOption includeOption, string id) { SigningKey = (RSACryptoServiceProvider)certificate.PrivateKey; SignedInfo.CanonicalizationMethod = Saml2SignedXml.XmlDsigExcC14NTransformUrl; //SignedInfo.SignatureMethod = SecurityAlgorithms.RsaSha256Signature; var reference = new Reference("#" + id); // reference.DigestMethod = SecurityAlgorithms.Sha1Digest; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); AddReference(reference); ComputeSignature(); KeyInfo = new KeyInfo(); KeyInfo.AddClause(new KeyInfoX509Data(certificate, includeOption)); }
private static XmlElement GerarAssinatura(XmlDocument doc, string infoElement, string signAtribute, X509Certificate2 certificado, bool comments = false, SignDigest digest = SignDigest.SHA1) { Guard.Against <ArgumentException>(!infoElement.IsEmpty() && doc.GetElementsByTagName(infoElement).Count != 1, "Referencia invalida ou não é unica."); //Adiciona Certificado ao Key Info var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificado)); //Seta chaves var signedDocument = new SignedXml(doc) { SigningKey = certificado.PrivateKey, KeyInfo = keyInfo, SignedInfo = { SignatureMethod = GetSignatureMethod(digest) } }; var uri = infoElement.IsEmpty() || signAtribute.IsEmpty() ? "" : $"#{doc.GetElementsByTagName(infoElement)[0].Attributes?[signAtribute]?.InnerText}"; // Cria referencia var reference = new Reference { Uri = uri, DigestMethod = GetDigestMethod(digest) }; // Adiciona transformação a referencia reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigC14NTransform(comments)); // Adiciona referencia ao xml signedDocument.AddReference(reference); // Calcula Assinatura signedDocument.ComputeSignature(); // Pega representação da assinatura return(signedDocument.GetXml()); }
private Legacy.KeyInfoEncryptedKey EncryptKey(byte[] key, RSA encryptionKey, string method, Legacy.KeyInfoClause encryptionKeyInfoClause) { var encryptionKeyInfo = new Legacy.KeyInfo(); encryptionKeyInfo.AddClause(encryptionKeyInfoClause); var cipherValue = Legacy.EncryptedXml.EncryptKey(key, encryptionKey, true); var encryptedKey = new Legacy.EncryptedKey { CipherData = new Legacy.CipherData { CipherValue = cipherValue }, EncryptionMethod = new Legacy.EncryptionMethod(method), KeyInfo = encryptionKeyInfo }; return(new Legacy.KeyInfoEncryptedKey { EncryptedKey = encryptedKey }); }
public void ApplySignature(SamlResponse response, X509Certificate2 certificate, XmlDocument document) { var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificate)); var signedXml = new SignedXml(document) { SigningKey = certificate.PrivateKey, KeyInfo = keyInfo }; var reference = new Reference(AssertionIdPrefix + response.Id); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(reference); signedXml.ComputeSignature(); var xml = signedXml.GetXml(); document.FindChild(AssertionElem).AppendChild(xml); }
public static void Sign(this XmlDocument xmlDocument, X509Certificate2 cert, bool includeKeyInfo) { if (xmlDocument == null) { throw new ArgumentNullException("xmlDocument"); } if (cert == null) { throw new ArgumentNullException("cert"); } var signedXml = new SignedXml(xmlDocument); // The transform XmlDsigExcC14NTransform and canonicalization method XmlDsigExcC14NTransformUrl is important for partially signed XML files // see: http://msdn.microsoft.com/en-us/library/system.security.cryptography.xml.signedxml.xmldsigexcc14ntransformurl(v=vs.110).aspx // The reference URI has to be set correctly to avoid assertion injections // For both, the ID/Reference and the Transform/Canonicalization see as well: // https://www.oasis-open.org/committees/download.php/35711/sstc-saml-core-errata-2.0-wd-06-diff.pdf section 5.4.2 and 5.4.3 signedXml.SigningKey = (RSACryptoServiceProvider)cert.PrivateKey; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; var reference = new Reference { Uri = "#" + xmlDocument.DocumentElement.GetAttribute("ID") }; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); signedXml.AddReference(reference); signedXml.ComputeSignature(); if (includeKeyInfo) { var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(cert)); signedXml.KeyInfo = keyInfo; } xmlDocument.DocumentElement.InsertAfter( xmlDocument.ImportNode(signedXml.GetXml(), true), xmlDocument.DocumentElement["Issuer", Saml2Namespaces.Saml2Name]); }
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 void SignXmlDocument(Stream sourceXmlFile, Stream destinationXmlFile, X509Certificate2 certificate) { // Carico il documento XML XmlDocument doc = new XmlDocument(); doc.Load(sourceXmlFile); // Preparo un DOMDocument che conterrà il risultato XmlDocument outputDocument = new XmlDocument(); // Recupero un riferimento all'intero contenuto del documento XML XmlNodeList elementsToSign = doc.SelectNodes(String.Format("/{0}", doc.DocumentElement.Name)); // Costruisco la firma SignedXml signedXml = new SignedXml(); System.Security.Cryptography.Xml.DataObject dataSignature = new System.Security.Cryptography.Xml.DataObject(); dataSignature.Data = elementsToSign; dataSignature.Id = doc.DocumentElement.Name; signedXml.AddObject(dataSignature); Reference reference = new Reference(); reference.Uri = String.Format("#{0}", dataSignature.Id); signedXml.AddReference(reference); if ((certificate != null) && (certificate.HasPrivateKey)) { signedXml.SigningKey = certificate.PrivateKey; KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificate)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); // Aggiungo la firma al nuovo documento di output outputDocument.AppendChild( outputDocument.ImportNode(signedXml.GetXml(), true)); outputDocument.Save(destinationXmlFile); } }
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 KeyInfoClause CreateEncryptedKeyClause(byte[] key, KeyInfo keyInfo) { if (!Crypto.IsSupportedAlgorithm(_credentials.Alg, _credentials.Key)) { throw new NotSupportedException(_credentials.Alg); } var keyWrap = Crypto.CreateKeyWrapProvider(_credentials.Key, _credentials.Alg); var cipherValue = keyWrap.WrapKey(key); var encryptedKey = new EncryptedKey { CipherData = new CipherData { CipherValue = cipherValue }, EncryptionMethod = new EncryptionMethod(_credentials.Alg), KeyInfo = keyInfo }; return(new KeyInfoEncryptedKey { EncryptedKey = encryptedKey }); }
public override void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); Id = Utils.GetAttribute(value, "Id", EncryptedXml.XmlEncNamespaceUrl); Type = Utils.GetAttribute(value, "Type", EncryptedXml.XmlEncNamespaceUrl); MimeType = Utils.GetAttribute(value, "MimeType", EncryptedXml.XmlEncNamespaceUrl); Encoding = Utils.GetAttribute(value, "Encoding", EncryptedXml.XmlEncNamespaceUrl); Recipient = Utils.GetAttribute(value, "Recipient", EncryptedXml.XmlEncNamespaceUrl); XmlNode encryptionMethodNode = value.SelectSingleNode("enc:EncryptionMethod", nsm); // EncryptionMethod EncryptionMethod = new EncryptionMethod(); if (encryptionMethodNode != null) { EncryptionMethod.LoadXml(encryptionMethodNode as XmlElement); } // Key Info KeyInfo = new KeyInfo(); XmlNode keyInfoNode = value.SelectSingleNode("ds:KeyInfo", nsm); if (keyInfoNode != null) { KeyInfo.LoadXml(keyInfoNode as XmlElement); } // CipherData XmlNode cipherDataNode = value.SelectSingleNode("enc:CipherData", nsm); if (cipherDataNode == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingCipherData")); } CipherData = new CipherData(); CipherData.LoadXml(cipherDataNode as XmlElement); // EncryptionProperties XmlNode encryptionPropertiesNode = value.SelectSingleNode("enc:EncryptionProperties", nsm); if (encryptionPropertiesNode != null) { // Select the EncryptionProperty elements inside the EncryptionProperties element XmlNodeList encryptionPropertyNodes = encryptionPropertiesNode.SelectNodes("enc:EncryptionProperty", nsm); if (encryptionPropertyNodes != null) { foreach (XmlNode node in encryptionPropertyNodes) { EncryptionProperty ep = new EncryptionProperty(); ep.LoadXml(node as XmlElement); EncryptionProperties.Add(ep); } } } // CarriedKeyName XmlNode carriedKeyNameNode = value.SelectSingleNode("enc:CarriedKeyName", nsm); if (carriedKeyNameNode != null) { CarriedKeyName = carriedKeyNameNode.InnerText; } // ReferenceList XmlNode referenceListNode = value.SelectSingleNode("enc:ReferenceList", nsm); if (referenceListNode != null) { // Select the DataReference elements inside the ReferenceList element XmlNodeList dataReferenceNodes = referenceListNode.SelectNodes("enc:DataReference", nsm); if (dataReferenceNodes != null) { foreach (XmlNode node in dataReferenceNodes) { DataReference dr = new DataReference(); dr.LoadXml(node as XmlElement); ReferenceList.Add(dr); } } // Select the KeyReference elements inside the ReferenceList element XmlNodeList keyReferenceNodes = referenceListNode.SelectNodes("enc:KeyReference", nsm); if (keyReferenceNodes != null) { foreach (XmlNode node in keyReferenceNodes) { KeyReference kr = new KeyReference(); kr.LoadXml(node as XmlElement); ReferenceList.Add(kr); } } } // Save away the cached value _cachedXml = value; }
public void LoadXml(XmlElement value) { // Make sure we don't get passed null if (value == null) { throw new ArgumentNullException(nameof(value)); } // Signature XmlElement signatureElement = value; if (!signatureElement.LocalName.Equals("Signature")) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature"); } // Id attribute -- optional _id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl); if (!Utils.VerifyAttributes(signatureElement, "Id")) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature"); } XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); int expectedChildNodes = 0; // SignedInfo XmlNodeList signedInfoNodes = signatureElement.SelectNodes("ds:SignedInfo", nsm); if (signedInfoNodes == null || signedInfoNodes.Count == 0 || signedInfoNodes.Count > 1) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo"); } XmlElement signedInfoElement = signedInfoNodes[0] as XmlElement; expectedChildNodes += signedInfoNodes.Count; SignedInfo = new SignedInfo(); SignedInfo.LoadXml(signedInfoElement); // SignatureValue XmlNodeList signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm); if (signatureValueNodes == null || signatureValueNodes.Count == 0 || signatureValueNodes.Count > 1) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue"); } XmlElement signatureValueElement = signatureValueNodes[0] as XmlElement; expectedChildNodes += signatureValueNodes.Count; _signatureValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText)); _signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl); if (!Utils.VerifyAttributes(signatureValueElement, "Id")) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue"); } // KeyInfo - optional single element XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm); _keyInfo = new KeyInfo(); if (keyInfoNodes != null) { if (keyInfoNodes.Count > 1) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "KeyInfo"); } foreach (XmlNode node in keyInfoNodes) { XmlElement keyInfoElement = node as XmlElement; if (keyInfoElement != null) { _keyInfo.LoadXml(keyInfoElement); } } expectedChildNodes += keyInfoNodes.Count; } // Object - zero or more elements allowed XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm); _embeddedObjects.Clear(); if (objectNodes != null) { foreach (XmlNode node in objectNodes) { XmlElement objectElement = node as XmlElement; if (objectElement != null) { DataObject dataObj = new DataObject(); dataObj.LoadXml(objectElement); _embeddedObjects.Add(dataObj); } } expectedChildNodes += objectNodes.Count; } // Select all elements that have Id attributes XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm); if (nodeList != null) { foreach (XmlNode node in nodeList) { _referencedItems.Add(node); } } // Verify that there aren't any extra nodes that aren't allowed if (signatureElement.SelectNodes("*").Count != expectedChildNodes) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature"); } }
public override void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } if ((value.LocalName != XmlEncryption.ElementNames.EncryptedData) || (value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl)) { throw new CryptographicException("Malformed EncryptedData element."); } else { EncryptionMethod = null; EncryptionMethod = null; EncryptionProperties.Clear(); Id = null; Type = null; MimeType = null; Encoding = null; foreach (XmlNode n in value.ChildNodes) { if (n is XmlWhitespace) { continue; } switch (n.LocalName) { case XmlEncryption.ElementNames.EncryptionMethod: EncryptionMethod = new EncryptionMethod(); EncryptionMethod.LoadXml((XmlElement)n); break; case XmlSignature.ElementNames.KeyInfo: KeyInfo = new KeyInfo(); KeyInfo.LoadXml((XmlElement)n); break; case XmlEncryption.ElementNames.CipherData: CipherData = new CipherData(); CipherData.LoadXml((XmlElement)n); break; case XmlEncryption.ElementNames.EncryptionProperties: foreach (XmlElement element in ((XmlElement)n).GetElementsByTagName(XmlEncryption.ElementNames.EncryptionProperty, EncryptedXml.XmlEncNamespaceUrl)) { EncryptionProperties.Add(new EncryptionProperty(element)); } break; } } if (value.HasAttribute(XmlEncryption.AttributeNames.Id)) { Id = value.Attributes [XmlEncryption.AttributeNames.Id].Value; } if (value.HasAttribute(XmlEncryption.AttributeNames.Type)) { Type = value.Attributes [XmlEncryption.AttributeNames.Type].Value; } if (value.HasAttribute(XmlEncryption.AttributeNames.MimeType)) { MimeType = value.Attributes [XmlEncryption.AttributeNames.MimeType].Value; } if (value.HasAttribute(XmlEncryption.AttributeNames.Encoding)) { Encoding = value.Attributes [XmlEncryption.AttributeNames.Encoding].Value; } } }
private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecryptor decryptor) { XmlElement encryptionMethod = null; XmlElement keyInfo = null; XmlElement cipherData = null; EncryptionMethod encryptionMethodObj = null; KeyInfo keyInfoObj = null; CipherData cipherDataObj = null; for (int i = 0, count = encryptedGrantList.Count; i < count; i++) { encryptionMethod = encryptedGrantList[i].SelectSingleNode("//r:encryptedGrant/enc:EncryptionMethod", _namespaceManager) as XmlElement; keyInfo = encryptedGrantList[i].SelectSingleNode("//r:encryptedGrant/dsig:KeyInfo", _namespaceManager) as XmlElement; cipherData = encryptedGrantList[i].SelectSingleNode("//r:encryptedGrant/enc:CipherData", _namespaceManager) as XmlElement; if ((encryptionMethod != null) && (keyInfo != null) && (cipherData != null)) { encryptionMethodObj = new EncryptionMethod(); keyInfoObj = new KeyInfo(); cipherDataObj = new CipherData(); encryptionMethodObj.LoadXml(encryptionMethod); keyInfoObj.LoadXml(keyInfo); cipherDataObj.LoadXml(cipherData); MemoryStream toDecrypt = null; Stream decryptedContent = null; StreamReader streamReader = null; try { toDecrypt = new MemoryStream(cipherDataObj.CipherValue); decryptedContent = _relDecryptor.Decrypt(encryptionMethodObj, keyInfoObj, toDecrypt); if ((decryptedContent == null) || (decryptedContent.Length == 0)) { throw new CryptographicException(SR.Cryptography_Xml_XrmlUnableToDecryptGrant); } streamReader = new StreamReader(decryptedContent); string clearContent = streamReader.ReadToEnd(); encryptedGrantList[i].ParentNode.InnerXml = clearContent; } finally { if (toDecrypt != null) { toDecrypt.Close(); } if (decryptedContent != null) { decryptedContent.Close(); } if (streamReader != null) { streamReader.Close(); } } encryptionMethodObj = null; keyInfoObj = null; cipherDataObj = null; } encryptionMethod = null; keyInfo = null; cipherData = null; } }
public static void SignXmlFile(string fileName, ref string signedContent, RSA key) { // Check the arguments. if (fileName == null) { throw new ArgumentNullException("fileName"); } if (signedContent == null) { throw new ArgumentNullException("signedFileName"); } if (key == null) { throw new ArgumentNullException("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)); doc.LoadXml(fileName); // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = key; // Get the signature object from the SignedXml object. System.Security.Cryptography.Xml.Signature XMLSignature = signedXml.Signature; // Create a reference to be signed. Pass "" // to specify that all of the current XML // document should be signed. System.Security.Cryptography.Xml.Reference reference = new System.Security.Cryptography.Xml.Reference(""); // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the Reference object to the Signature object. XMLSignature.SignedInfo.AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). System.Security.Cryptography.Xml.KeyInfo keyInfo = new System.Security.Cryptography.Xml.KeyInfo(); keyInfo.AddClause(new RSAKeyValue((RSA)key)); // Add the KeyInfo object to the Reference object. XMLSignature.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); } signedContent = doc.InnerXml; }
/// <summary> /// Takes the configuration class and converts it to a SAML2.0 metadata document. /// </summary> /// <param name="config">The config.</param> /// <param name="keyInfo">The keyInfo.</param> private void ConvertToMetadata(Saml2Configuration config) { var entity = CreateDefaultEntity(); entity.EntityId = config.ServiceProvider.Id; if (config.ServiceProvider.UseValidUntil) { entity.ValidUntil = DateTime.Now.AddDays(7); } var serviceProviderDescriptor = new SpSsoDescriptor { ProtocolSupportEnumeration = new[] { Saml20Constants.Protocol }, AuthnRequestsSigned = XmlConvert.ToString(config.ServiceProvider.AuthNRequestsSigned), WantAssertionsSigned = XmlConvert.ToString(config.ServiceProvider.WantAssertionsSigned) }; if (config.ServiceProvider.NameIdFormats.Count > 0) { serviceProviderDescriptor.NameIdFormat = new string[config.ServiceProvider.NameIdFormats.Count]; var count = 0; foreach (var elem in config.ServiceProvider.NameIdFormats) { serviceProviderDescriptor.NameIdFormat[count++] = elem.Format; } } var baseUrl = new Uri(config.ServiceProvider.Server); var logoutServiceEndpoints = new List <Endpoint>(); var signonServiceEndpoints = new List <IndexedEndpoint>(); var artifactResolutionEndpoints = new List <IndexedEndpoint>(2); // Include endpoints. foreach (var endpoint in config.ServiceProvider.Endpoints) { if (endpoint.Type == EndpointType.SignOn) { var loginEndpoint = new IndexedEndpoint { Index = endpoint.Index, IsDefault = endpoint.Default, Location = new Uri(baseUrl, endpoint.LocalPath).ToString(), Binding = GetBinding(endpoint.Binding, Saml20Constants.ProtocolBindings.HttpPost) }; signonServiceEndpoints.Add(loginEndpoint); if (config.ServiceProvider.IncludeArtifactResolutionEndpoints) { var artifactSignonEndpoint = new IndexedEndpoint { Binding = Saml20Constants.ProtocolBindings.HttpSoap, Index = loginEndpoint.Index, Location = loginEndpoint.Location }; artifactResolutionEndpoints.Add(artifactSignonEndpoint); } continue; } if (endpoint.Type == EndpointType.Logout) { var location = new Uri(baseUrl, endpoint.LocalPath).ToString(); var logoutEndpoint = new Endpoint { Location = location, ResponseLocation = location, Binding = GetBinding(endpoint.Binding, Saml20Constants.ProtocolBindings.HttpPost) }; logoutServiceEndpoints.Add(logoutEndpoint); if (config.ServiceProvider.IncludeArtifactResolutionEndpoints) { var artifactLogoutEndpoint = new IndexedEndpoint { Binding = Saml20Constants.ProtocolBindings.HttpSoap, Index = endpoint.Index, Location = logoutEndpoint.Location }; artifactResolutionEndpoints.Add(artifactLogoutEndpoint); } continue; } } serviceProviderDescriptor.SingleLogoutService = logoutServiceEndpoints.ToArray(); serviceProviderDescriptor.AssertionConsumerService = signonServiceEndpoints.ToArray(); // Attribute consuming service. if (config.Metadata.RequestedAttributes.Count > 0) { var attConsumingService = new AttributeConsumingService(); serviceProviderDescriptor.AttributeConsumingService = new[] { attConsumingService }; attConsumingService.Index = signonServiceEndpoints[0].Index; attConsumingService.IsDefault = true; attConsumingService.ServiceName = new[] { new LocalizedName("SP", "en") }; attConsumingService.RequestedAttribute = new RequestedAttribute[config.Metadata.RequestedAttributes.Count]; for (var i = 0; i < config.Metadata.RequestedAttributes.Count; i++) { attConsumingService.RequestedAttribute[i] = new RequestedAttribute { Name = config.Metadata.RequestedAttributes[i].Name, NameFormat = SamlAttribute.NameformatBasic }; if (config.Metadata.RequestedAttributes[i].IsRequired) { attConsumingService.RequestedAttribute[i].IsRequired = true; } } } else { serviceProviderDescriptor.AttributeConsumingService = new AttributeConsumingService[0]; } if (config.Metadata == null || !config.Metadata.ExcludeArtifactEndpoints) { serviceProviderDescriptor.ArtifactResolutionService = artifactResolutionEndpoints.ToArray(); } entity.Items = new object[] { serviceProviderDescriptor }; // Keyinfo var keySigning = new KeyDescriptor(); var keyEncryption = new KeyDescriptor(); serviceProviderDescriptor.KeyDescriptor = new[] { keySigning, keyEncryption }; keySigning.Use = KeyTypes.Signing; keySigning.UseSpecified = true; keyEncryption.Use = KeyTypes.Encryption; keyEncryption.UseSpecified = true; var keyinfo = new System.Security.Cryptography.Xml.KeyInfo(); var keyClause = new System.Security.Cryptography.Xml.KeyInfoX509Data(config.ServiceProvider.SigningCertificate, X509IncludeOption.EndCertOnly); keyinfo.AddClause(keyClause); // Ugly conversion between the .Net framework classes and our classes ... avert your eyes!! keySigning.KeyInfo = Serialization.DeserializeFromXmlString <Schema.XmlDSig.KeyInfo>(keyinfo.GetXml().OuterXml); keyEncryption.KeyInfo = keySigning.KeyInfo; // apply the <Organization> element if (config.Metadata.Organization != null) { entity.Organization = new Schema.Metadata.Organization { OrganizationName = new[] { new LocalizedName { Value = config.Metadata.Organization.Name, Language = "en" } }, OrganizationDisplayName = new[] { new LocalizedName { Value = config.Metadata.Organization.DisplayName, Language = "en" } }, OrganizationURL = new[] { new LocalizedURI { Value = config.Metadata.Organization.Url, Language = "en" } } }; } if (config.Metadata.Contacts != null && config.Metadata.Contacts.Any()) { entity.ContactPerson = config.Metadata.Contacts.Select(x => new Schema.Metadata.Contact { ContactType = (Schema.Metadata.ContactType) ((int)x.Type), Company = x.Company, GivenName = x.GivenName, SurName = x.SurName, EmailAddress = new[] { x.Email }, TelephoneNumber = new[] { x.Phone } }).ToArray(); } }
public override void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); Id = Utils.GetAttribute(value, "Id", EncryptedXml.XmlEncNamespaceUrl); Type = Utils.GetAttribute(value, "Type", EncryptedXml.XmlEncNamespaceUrl); MimeType = Utils.GetAttribute(value, "MimeType", EncryptedXml.XmlEncNamespaceUrl); Encoding = Utils.GetAttribute(value, "Encoding", EncryptedXml.XmlEncNamespaceUrl); XmlNode encryptionMethodNode = value.SelectSingleNode("enc:EncryptionMethod", nsm); // EncryptionMethod EncryptionMethod = new EncryptionMethod(); if (encryptionMethodNode != null) { EncryptionMethod.LoadXml(encryptionMethodNode as XmlElement); } // Key Info KeyInfo = new KeyInfo(); XmlNode keyInfoNode = value.SelectSingleNode("ds:KeyInfo", nsm); if (keyInfoNode != null) { KeyInfo.LoadXml(keyInfoNode as XmlElement); } // CipherData XmlNode cipherDataNode = value.SelectSingleNode("enc:CipherData", nsm); if (cipherDataNode == null) { throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData); } CipherData = new CipherData(); CipherData.LoadXml(cipherDataNode as XmlElement); // EncryptionProperties XmlNode encryptionPropertiesNode = value.SelectSingleNode("enc:EncryptionProperties", nsm); if (encryptionPropertiesNode != null) { // Select the EncryptionProperty elements inside the EncryptionProperties element XmlNodeList encryptionPropertyNodes = encryptionPropertiesNode.SelectNodes("enc:EncryptionProperty", nsm); if (encryptionPropertyNodes != null) { foreach (XmlNode node in encryptionPropertyNodes) { EncryptionProperty ep = new EncryptionProperty(); ep.LoadXml(node as XmlElement); EncryptionProperties.Add(ep); } } } // Save away the cached value _cachedXml = value; }
protected EncryptedType() { cipherData = new CipherData(); encryptionProperties = new EncryptionPropertyCollection(); keyInfo = new KeyInfo(); }
internal XmlElement GetXml(XmlDocument document) { // Create the EncryptedKey element XmlElement encryptedKeyElement = (XmlElement)document.CreateElement("EncryptedKey", EncryptedXml.XmlEncNamespaceUrl); // Deal with attributes if (!string.IsNullOrEmpty(Id)) { encryptedKeyElement.SetAttribute("Id", Id); } if (!string.IsNullOrEmpty(Type)) { encryptedKeyElement.SetAttribute("Type", Type); } if (!string.IsNullOrEmpty(MimeType)) { encryptedKeyElement.SetAttribute("MimeType", MimeType); } if (!string.IsNullOrEmpty(Encoding)) { encryptedKeyElement.SetAttribute("Encoding", Encoding); } if (!string.IsNullOrEmpty(Recipient)) { encryptedKeyElement.SetAttribute("Recipient", Recipient); } // EncryptionMethod if (EncryptionMethod != null) { encryptedKeyElement.AppendChild(EncryptionMethod.GetXml(document)); } // KeyInfo if (KeyInfo.Count > 0) { encryptedKeyElement.AppendChild(KeyInfo.GetXml(document)); } // CipherData if (CipherData == null) { throw new CryptographicException(SR.Cryptography_Xml_MissingCipherData); } encryptedKeyElement.AppendChild(CipherData.GetXml(document)); // EncryptionProperties if (EncryptionProperties.Count > 0) { XmlElement encryptionPropertiesElement = document.CreateElement("EncryptionProperties", EncryptedXml.XmlEncNamespaceUrl); for (int index = 0; index < EncryptionProperties.Count; index++) { EncryptionProperty ep = EncryptionProperties.Item(index); encryptionPropertiesElement.AppendChild(ep.GetXml(document)); } encryptedKeyElement.AppendChild(encryptionPropertiesElement); } // ReferenceList if (ReferenceList.Count > 0) { XmlElement referenceListElement = document.CreateElement("ReferenceList", EncryptedXml.XmlEncNamespaceUrl); for (int index = 0; index < ReferenceList.Count; index++) { referenceListElement.AppendChild(ReferenceList[index].GetXml(document)); } encryptedKeyElement.AppendChild(referenceListElement); } // CarriedKeyName if (CarriedKeyName != null) { XmlElement carriedKeyNameElement = (XmlElement)document.CreateElement("CarriedKeyName", EncryptedXml.XmlEncNamespaceUrl); XmlText carriedKeyNameText = document.CreateTextNode(CarriedKeyName); carriedKeyNameElement.AppendChild(carriedKeyNameText); encryptedKeyElement.AppendChild(carriedKeyNameElement); } return(encryptedKeyElement); }
//public static string RetornarXmlFirmado(string xmlString, string rutaCertificado, string claveCertificado, out string hash) //{ // hash = null; // XmlDocument documentXml = new XmlDocument(); // documentXml.PreserveWhitespace = true; // documentXml.LoadXml(xmlString); // var nodoExtension = documentXml.GetElementsByTagName("ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2").Item(0); // if (nodoExtension == null) // { // throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML"); // } // nodoExtension.RemoveAll(); // SignedXml firmado = new SignedXml(documentXml); // var xmlSignature = firmado.Signature; // byte[] certificadoByte = File.ReadAllBytes(rutaCertificado); // X509Certificate2 certificado = new X509Certificate2(); // //certificado.Import(certificadoByte, claveCertificado, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); // certificado.Import(certificadoByte, claveCertificado, X509KeyStorageFlags.Exportable); // firmado.SigningKey = certificado.GetRSAPrivateKey(); // //firmado.SigningKey = (RSA)certificado.PrivateKey; // //firmado.SigningKey = certificado.PrivateKey; // //digest info agregada en la seccion firma // var env = new XmlDsigEnvelopedSignatureTransform(); // Reference reference = new Reference(); // reference.AddTransform(env); // reference.Uri = ""; // firmado.AddReference(reference); // firmado.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; // reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; // var keyInfoData = new KeyInfoX509Data(certificado); // keyInfoData.AddSubjectName(certificado.Subject); // // info para la llave publica // KeyInfo keyInfo = new KeyInfo(); // keyInfo.AddClause(keyInfoData); // //keyInfo.sub // xmlSignature.KeyInfo = keyInfo; // xmlSignature.Id = "signatureKG"; // firmado.ComputeSignature(); // // Recuperamos el valor Hash de la firma para este documento. // if (reference.DigestValue != null) // { // hash = Convert.ToBase64String(reference.DigestValue); // } // XmlNode xmlNodeFirmado = firmado.GetXml(); // xmlNodeFirmado.Prefix = "ds"; // //XmlNode xmlNodeContent = documentXml.CreateElement("ext", "ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"); // //xmlNodeContent.AppendChild(xmlNodeFirmado); // //XmlNode xmlNode = documentXml.CreateElement("ext", "UBLExtension", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"); // //xmlNode.AppendChild(xmlNodeContent); // nodoExtension.AppendChild(xmlNodeFirmado); // var settings = new XmlWriterSettings() // { // Encoding = Encoding.UTF8, // Indent = true, // IndentChars = "\t", // NewLineChars = Environment.NewLine // }; // string resultado = String.Empty; // using (var memDoc = new MemoryStream()) // { // using (var writer = XmlWriter.Create(memDoc, settings)) // { // //XDocument xDocument = XDocument.Parse(documentXml.OuterXml); // //xDocument.WriteTo(writer); // documentXml.WriteTo(writer); // } // //resultado = Encoding.Unicode.GetString(memDoc.ToArray()); // //resultado = Encoding.GetEncoding("ISO-8859-1").GetString(memDoc.ToArray()); // //resultado = Convert.ToBase64String(memDoc.ToArray()); // resultado = Encoding.UTF8.GetString(memDoc.ToArray()); // } // return resultado; //} public static string RetornarXmlFirmado(string prefijoComprobanteBusqueda, string tnsString, string xmlString, string rutaCertificado, string claveCertificado, out string hash) { hash = null; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; xmlDocument.LoadXml(xmlString); X509Certificate2 certificado = new X509Certificate2(rutaCertificado, claveCertificado); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDocument.NameTable); nsMgr.AddNamespace("tns", tnsString); nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"); XmlElement elem = xmlDocument.CreateElement("ext:ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"); xmlDocument.SelectSingleNode($"{prefijoComprobanteBusqueda}/ext:UBLExtensions/ext:UBLExtension", nsMgr).AppendChild(elem); SignedXml signedXml = new SignedXml(xmlDocument); signedXml.SigningKey = certificado.GetRSAPrivateKey(); System.Security.Cryptography.Xml.KeyInfo KeyInfo = new System.Security.Cryptography.Xml.KeyInfo(); System.Security.Cryptography.Xml.Reference Reference = new System.Security.Cryptography.Xml.Reference(); Reference.Uri = ""; Reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(Reference); X509Chain X509Chain = new X509Chain(); X509Chain.Build(certificado); X509ChainElement local_element = X509Chain.ChainElements[0]; KeyInfoX509Data x509Data = new KeyInfoX509Data(local_element.Certificate); string subjectName = local_element.Certificate.Subject; x509Data.AddSubjectName(subjectName); KeyInfo.AddClause(x509Data); signedXml.Signature.Id = "signatureKG"; signedXml.KeyInfo = KeyInfo; signedXml.ComputeSignature(); XmlElement signature = signedXml.GetXml(); XmlNode dg = signature.GetElementsByTagName("DigestValue", "http://www.w3.org/2000/09/xmldsig#")[0]; XmlNode sg = signature.GetElementsByTagName("SignatureValue", "http://www.w3.org/2000/09/xmldsig#")[0]; hash = dg.InnerText; //SignatureValue = sg.InnerText; signature.Prefix = "ds"; //SetPrefix("ds", signature); elem.AppendChild(signature); MemoryStream msXMLFirmado = new MemoryStream(); xmlDocument.Save(msXMLFirmado); //msXMLFirmado.Position = 1; return(Encoding.UTF8.GetString(msXMLFirmado.ToArray()).Substring(1)); }
public override void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } if ((value.LocalName != XmlEncryption.ElementNames.EncryptedKey) || (value.NamespaceURI != EncryptedXml.XmlEncNamespaceUrl)) { throw new CryptographicException("Malformed EncryptedKey element."); } else { EncryptionMethod = null; EncryptionMethod = null; EncryptionProperties.Clear(); ReferenceList.Clear(); CarriedKeyName = null; Id = null; Type = null; MimeType = null; Encoding = null; Recipient = null; foreach (XmlNode n in value.ChildNodes) { if (n is XmlWhitespace) { continue; } switch (n.LocalName) { case XmlEncryption.ElementNames.EncryptionMethod: EncryptionMethod = new EncryptionMethod(); EncryptionMethod.LoadXml((XmlElement)n); break; case XmlSignature.ElementNames.KeyInfo: KeyInfo = new KeyInfo(); KeyInfo.LoadXml((XmlElement)n); break; case XmlEncryption.ElementNames.CipherData: CipherData = new CipherData(); CipherData.LoadXml((XmlElement)n); break; case XmlEncryption.ElementNames.EncryptionProperties: foreach (XmlElement element in ((XmlElement)n).GetElementsByTagName(XmlEncryption.ElementNames.EncryptionProperty, EncryptedXml.XmlEncNamespaceUrl)) { EncryptionProperties.Add(new EncryptionProperty(element)); } break; case XmlEncryption.ElementNames.ReferenceList: foreach (XmlNode r in ((XmlElement)n).ChildNodes) { if (r is XmlWhitespace) { continue; } switch (r.LocalName) { case XmlEncryption.ElementNames.DataReference: DataReference dr = new DataReference(); dr.LoadXml((XmlElement)r); AddReference(dr); break; case XmlEncryption.ElementNames.KeyReference: KeyReference kr = new KeyReference(); kr.LoadXml((XmlElement)r); AddReference(kr); break; } } break; case XmlEncryption.ElementNames.CarriedKeyName: CarriedKeyName = ((XmlElement)n).InnerText; break; } } if (value.HasAttribute(XmlEncryption.AttributeNames.Id)) { Id = value.Attributes [XmlEncryption.AttributeNames.Id].Value; } if (value.HasAttribute(XmlEncryption.AttributeNames.Type)) { Type = value.Attributes [XmlEncryption.AttributeNames.Type].Value; } if (value.HasAttribute(XmlEncryption.AttributeNames.MimeType)) { MimeType = value.Attributes [XmlEncryption.AttributeNames.MimeType].Value; } if (value.HasAttribute(XmlEncryption.AttributeNames.Encoding)) { Encoding = value.Attributes [XmlEncryption.AttributeNames.Encoding].Value; } if (value.HasAttribute(XmlEncryption.AttributeNames.Recipient)) { Encoding = value.Attributes [XmlEncryption.AttributeNames.Recipient].Value; } } }
public void LoadXml(XmlElement value) { // Make sure we don't get passed null if (value == null) { throw new ArgumentNullException("value"); } // Signature XmlElement signatureElement = value; if (!signatureElement.LocalName.Equals("Signature")) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature"); } // Id attribute -- optional m_id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); // SignedInfo XmlElement signedInfoElement = signatureElement.SelectSingleNode("ds:SignedInfo", nsm) as XmlElement; if (signedInfoElement == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo"); } this.SignedInfo = new SignedInfo(); this.SignedInfo.LoadXml(signedInfoElement); // SignatureValue XmlElement signatureValueElement = signatureElement.SelectSingleNode("ds:SignatureValue", nsm) as XmlElement; if (signatureValueElement == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo/SignatureValue"); } m_signatureValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText)); m_signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl); XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm); m_keyInfo = new KeyInfo(); if (keyInfoNodes != null) { foreach (XmlNode node in keyInfoNodes) { XmlElement keyInfoElement = node as XmlElement; if (keyInfoElement != null) { m_keyInfo.LoadXml(keyInfoElement); } } } XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm); m_embeddedObjects.Clear(); if (objectNodes != null) { foreach (XmlNode node in objectNodes) { XmlElement objectElement = node as XmlElement; if (objectElement != null) { DataObject dataObj = new DataObject(); dataObj.LoadXml(objectElement); m_embeddedObjects.Add(dataObj); } } } // Select all elements that have Id attributes XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm); if (nodeList != null) { foreach (XmlNode node in nodeList) { m_referencedItems.Add(node); } } }
internal XmlElement GetXml(XmlDocument document) { if (CipherData == null) { throw new CryptographicException("Cipher data is not specified."); } XmlElement xel = document.CreateElement(XmlEncryption.ElementNames.EncryptedKey, EncryptedXml.XmlEncNamespaceUrl); if (EncryptionMethod != null) { xel.AppendChild(EncryptionMethod.GetXml(document)); } if (KeyInfo != null) { xel.AppendChild(document.ImportNode(KeyInfo.GetXml(), true)); } if (CipherData != null) { xel.AppendChild(CipherData.GetXml(document)); } if (EncryptionProperties.Count > 0) { XmlElement xep = document.CreateElement(XmlEncryption.ElementNames.EncryptionProperties, EncryptedXml.XmlEncNamespaceUrl); foreach (EncryptionProperty p in EncryptionProperties) { xep.AppendChild(p.GetXml(document)); } xel.AppendChild(xep); } if (ReferenceList.Count > 0) { XmlElement xrl = document.CreateElement(XmlEncryption.ElementNames.ReferenceList, EncryptedXml.XmlEncNamespaceUrl); foreach (EncryptedReference er in ReferenceList) { xrl.AppendChild(er.GetXml(document)); } xel.AppendChild(xrl); } if (CarriedKeyName != null) { XmlElement xck = document.CreateElement(XmlEncryption.ElementNames.CarriedKeyName, EncryptedXml.XmlEncNamespaceUrl); xck.InnerText = CarriedKeyName; xel.AppendChild(xck); } if (Id != null) { xel.SetAttribute(XmlEncryption.AttributeNames.Id, Id); } if (Type != null) { xel.SetAttribute(XmlEncryption.AttributeNames.Type, Type); } if (MimeType != null) { xel.SetAttribute(XmlEncryption.AttributeNames.MimeType, MimeType); } if (Encoding != null) { xel.SetAttribute(XmlEncryption.AttributeNames.Encoding, Encoding); } if (Recipient != null) { xel.SetAttribute(XmlEncryption.AttributeNames.Recipient, Recipient); } return(xel); }
/// <summary> /// Message signing /// </summary> public virtual byte[] Sign( ISignableMessage message, X509Configuration x509Configuration) { if (message == null) { throw new ArgumentNullException("message"); } if (x509Configuration == null || x509Configuration.SignatureCertificate == null ) { throw new ArgumentNullException("certificate"); } // first, serialize to XML var messageBody = this.messageSerializer.Serialize(message, new MessageSerializationParameters() { ShouldBase64Encode = false, ShouldDeflate = false }); var xml = new XmlDocument(); xml.LoadXml(messageBody); // sign the node with the id var reference = new Reference("#" + message.ID); var envelope = new XmlDsigEnvelopedSignatureTransform(true); reference.AddTransform(envelope); // canonicalization var c14 = new XmlDsigExcC14NTransform(); c14.Algorithm = SignedXml.XmlDsigExcC14NTransformUrl; reference.AddTransform(c14); // some more spells depending on SHA1 vs SHA256 var signed = new SignedXml(xml); signed.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; switch (x509Configuration.SignatureAlgorithm) { case SignatureAlgorithm.SHA1: signed.SigningKey = x509Configuration.SignatureCertificate.PrivateKey; signed.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url; reference.DigestMethod = SignedXml.XmlDsigSHA1Url; break; case SignatureAlgorithm.SHA256: signed.SigningKey = x509Configuration.SignatureCertificate.ToSha256PrivateKey(); signed.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA256Url; reference.DigestMethod = SignedXml.XmlDsigSHA256Url; break; } if (x509Configuration.IncludeKeyInfo) { var key = new System.Security.Cryptography.Xml.KeyInfo(); var keyData = new KeyInfoX509Data(x509Configuration.SignatureCertificate); key.AddClause(keyData); signed.KeyInfo = key; } // show the reference signed.AddReference(reference); // create the signature signed.ComputeSignature(); var signature = signed.GetXml(); // insert the signature into the document var element = xml.DocumentElement.ChildNodes[0]; xml.DocumentElement.InsertAfter(xml.ImportNode(signature, true), element); // log new LoggerFactory().For(this).Debug(Event.SignedMessage, xml.OuterXml); // convert return(this.encoding.GetBytes(xml.OuterXml)); }