public void Sample2() { using (Aes aes = Aes.Create()) { byte[] keydata = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640="); aes.Mode = CipherMode.CBC; aes.KeySize = 256; aes.Key = keydata; aes.Padding = PaddingMode.Zeros; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(TestHelpers.LoadResourceStream("System.Security.Cryptography.Xml.Tests.EncryptedXmlSample2.xml")); EncryptedXml encxml = new EncryptedXml(doc); EncryptedData edata = new EncryptedData(); edata.LoadXml(doc.DocumentElement); encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, aes)); } }
private void DecryptDocument(X509Certificate2 decryptionSertificate) { var encryptedNode = ResponseContainer.EncryptedBody; if (encryptedNode == null) { return; } var encryptedXml = new EncryptedXml(ResponseContainer.Envelope); var encryptedData = new EncryptedData(); encryptedData.LoadXml(encryptedNode); var aes = AesManaged(decryptionSertificate); encryptedXml.ReplaceData(encryptedNode, encryptedXml.DecryptData(encryptedData, aes)); }
public void Sample2() { RijndaelManaged aes = new RijndaelManaged(); aes.Mode = CipherMode.CBC; aes.KeySize = 256; aes.Key = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640="); aes.Padding = PaddingMode.Zeros; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load("Test/System.Security.Cryptography.Xml/EncryptedXmlSample2.xml"); EncryptedXml encxml = new EncryptedXml(doc); EncryptedData edata = new EncryptedData(); edata.LoadXml(doc.DocumentElement); encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, aes)); }
public void Sample2() { using (Aes aes = Aes.Create()) { aes.Mode = CipherMode.CBC; aes.KeySize = 256; // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Unit test key.")] aes.Key = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640="); aes.Padding = PaddingMode.Zeros; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(TestHelpers.LoadResourceStream("System.Security.Cryptography.Xml.Tests.EncryptedXmlSample2.xml")); EncryptedXml encxml = new EncryptedXml(doc); EncryptedData edata = new EncryptedData(); edata.LoadXml(doc.DocumentElement); encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, aes)); } }
/// <summary> /// Decrypt document /// </summary> /// <param name="Doc">XmlDocument to decrypt</param> /// <param name="Alg">Encryption key to use</param> private static void Decrypt(XmlDocument Doc, SymmetricAlgorithm Alg) { // Check the arguments. if (Doc == null) { throw new ArgumentNullException("Doc"); } if (Alg == null) { throw new ArgumentNullException("Alg"); } // Find the EncryptedData element in the XmlDocument. //XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; XmlNodeList lst = Doc.GetElementsByTagName("EncryptedData"); for (int i = lst.Count - 1; i >= 0; i--) { XmlElement encryptedElement = (XmlElement)lst[i]; // If the EncryptedData element was not found, throw an exception. if (encryptedElement == null) { throw new XmlException("The EncryptedData element was not found."); } // Create an EncryptedData object and populate it. EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(); // Decrypt the element using the symmetric key. byte[] rgbOutput = exml.DecryptData(edElement, Alg); // Replace the encryptedData element with the plaintext XML element. exml.ReplaceData(encryptedElement, rgbOutput); } }
public bool DecryptBody(XmlDocument xmlDoc) { Algorithm keyEncryptionAlgorithm = _soapEnvelopeConfiguration.ApplyElement(Direction.Incoming, Usage.KeyEncryption).Algorithm; X509Certificate2 cert = _certstore.ClientEncryptionCertificate(); RSACryptoServiceProvider privateKeyProvider = (RSACryptoServiceProvider)cert.PrivateKey; // Get encrypted key var encryptedKeyNodes = xmlDoc.GetElementsByTagName("xenc:EncryptedKey"); if (encryptedKeyNodes.Count == 0) { return(false); } var encryptedKeyElement = encryptedKeyNodes[0] as XmlElement; EncryptedKey encKey = new EncryptedKey(); encKey.LoadXml(encryptedKeyElement); // Decrypt key bool useOaep; encKey.EncryptionMethod = CalculateEncryptedKey(keyEncryptionAlgorithm, out useOaep); var decryptedKey = EncryptedXml.DecryptKey(encKey.CipherData.CipherValue, privateKeyProvider, useOaep); // Create tripledes key var sessionKey = TripleDES.Create(); sessionKey.Key = decryptedKey; // Get encrypted data XmlElement encryptedElement = xmlDoc.GetElementsByTagName("xenc:EncryptedData")[0] as XmlElement; EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); EncryptedXml exml = new EncryptedXml(xmlDoc); var decryptedData = exml.DecryptData(edElement, sessionKey); exml.ReplaceData(encryptedElement, decryptedData); return(true); }
public string Decrypt(string cxFileName) { var Doc = cipherXmlDoc_; Doc.Load(cxFileName); SymmetricAlgorithm Alg = rijndaelManaged_; // Check the arguments. if (Doc == null) { throw new ArgumentNullException("Doc"); } if (Alg == null) { throw new ArgumentNullException("Alg"); } // Find the EncryptedData element in the XmlDocument. XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; // If the EncryptedData element was not found, throw an exception. if (encryptedElement == null) { throw new XmlException("The EncryptedData element was not found."); } // Create an EncryptedData object and populate it. EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(); // Decrypt the element using the symmetric key. byte[] rgbOutput = exml.DecryptData(edElement, Alg); // Replace the encryptedData element with the plaintext XML element. exml.ReplaceData(encryptedElement, rgbOutput); return(Doc.InnerXml); }
private static void DecryptXmlElement(XmlDocument Doc, SymmetricAlgorithm Alg) { if (Doc == null || Alg == null) { throw new ArgumentNullException("NullArg"); } XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; if (encryptedElement == null) { throw new XmlException("The EncryptedData element was not found."); } EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); EncryptedXml exml = new EncryptedXml(); byte[] rgbOutput = exml.DecryptData(edElement, Alg); exml.ReplaceData(encryptedElement, rgbOutput); }
public void Sample2() { RijndaelManaged aes = new RijndaelManaged(); aes.Mode = CipherMode.CBC; aes.KeySize = 256; // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Not a secret.")] aes.Key = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640="); aes.Padding = PaddingMode.Zeros; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(TestResourceHelper.GetFullPathOfResource("Test/System.Security.Cryptography.Xml/EncryptedXmlSample2.xml")); EncryptedXml encxml = new EncryptedXml(doc); EncryptedData edata = new EncryptedData(); edata.LoadXml(doc.DocumentElement); encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, aes)); }
public void Sample2() { var aes = CipherUtilities.GetCipher("AES/CBC/ZEROBYTEPADDING"); var random = new SecureRandom(); var ivdata = new byte[aes.GetBlockSize()]; var keydata = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640="); random.NextBytes(ivdata); var param = new ParametersWithIV(new KeyParameter(keydata), ivdata); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(TestHelpers.LoadResourceStream("Org.BouncyCastle.Crypto.Xml.Tests.EncryptedXmlSample2.xml")); EncryptedXml encxml = new EncryptedXml(doc); EncryptedData edata = new EncryptedData(); edata.LoadXml(doc.DocumentElement); encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, param)); }
// Расшифрование узла XML документа на симметричном ключе private static void Decrypt(string srcName, string destName, SymmetricAlgorithm Alg) { // Создаем новый объект xml документа. XmlDocument xmlDoc = new XmlDocument(); // Пробельные символы участвуют в вычислении подписи и должны быть сохранены для совместимости с другими реализациями. xmlDoc.PreserveWhitespace = true; // Загружаем в объект созданный XML документ. xmlDoc.Load(srcName); // Ищем узел для расшифрования. XmlElement encryptedElement = xmlDoc.GetElementsByTagName( "EncryptedData")[0] as XmlElement; if (encryptedElement == null) { throw new XmlException("Узел EncryptedData не найден"); } // Создаем объект EncryptedData. EncryptedData edElement = new EncryptedData(); // и загружаем в него зашифрованный узел edElement.LoadXml(encryptedElement); // Создаем объект EncryptedXml EncryptedXml exml = new EncryptedXml(); // Расшифровываем элемент используя // симметричный ключ. byte[] rgbOutput = exml.DecryptData(edElement, Alg); // Заменяем зашифрованный узел расшифрованным exml.ReplaceData(encryptedElement, rgbOutput); // Сохраняем расшифрованный документ. xmlDoc.Save(destName); }
void AssertDecryption1(string resourceName) { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(LoadResourceStream(resourceName)); EncryptedXml encxml = new EncryptedXml(doc); using (RSA rsa = new X509Certificate2(Convert.FromBase64String(SamplePfx), "mono").PrivateKey as RSA) { Assert.NotNull(rsa); XmlNamespaceManager nm = new XmlNamespaceManager(doc.NameTable); nm.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope"); nm.AddNamespace("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); nm.AddNamespace("e", EncryptedXml.XmlEncNamespaceUrl); XmlElement el = doc.SelectSingleNode("/s:Envelope/s:Header/o:Security/e:EncryptedKey", nm) as XmlElement; EncryptedKey ekey = new EncryptedKey(); ekey.LoadXml(el); byte[] key = rsa.Decrypt(ekey.CipherData.CipherValue, RSAEncryptionPadding.OaepSHA1); using (Aes aes = Aes.Create()) { aes.Key = key; aes.Mode = CipherMode.CBC; ArrayList al = new ArrayList(); foreach (XmlElement ed in doc.SelectNodes("//e:EncryptedData", nm)) { al.Add(ed); } foreach (XmlElement ed in al) { EncryptedData edata = new EncryptedData(); edata.LoadXml(ed); encxml.ReplaceData(ed, encxml.DecryptData(edata, aes)); } } } }
public static String DecryptXML(String xml, SymmetricAlgorithm key = null) { if (String.IsNullOrEmpty(xml)) { throw new ArgumentNullException("xml"); } if (key == null) { key = DefaultCryptographyKey; } var xmlDoc = default(XmlDocument); var element = default(XmlElement); var edElement = default(EncryptedData); var exml = default(EncryptedXml); var rgbOutput = default(Byte[]); xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); element = xmlDoc.DocumentElement; // Create an EncryptedData object and populate it. edElement = new EncryptedData(); Contract.Assert(element != null, "element != null"); edElement.LoadXml(element); // Create a new EncryptedXml object. exml = new EncryptedXml(); // Decrypt the element using the symmetric key. rgbOutput = exml.DecryptData(edElement, key); // Replace the encryptedData element with the plaintext XML element. exml.ReplaceData(element, rgbOutput); return(xmlDoc.OuterXml); }
/// <summary> /// Decrypts a list of elements using the cipher key. /// </summary> /// <param name="encryptedDataElems">Elements to decrypt.</param> /// <param name="cipherKey">Cipher key.</param> public void Decrypt(IList <XmlElement> encryptedDataElems, byte[] cipherKey) { ArgumentUtils.CheckNotNullNorEmpty(encryptedDataElems, "encryptedDataElems"); ArgumentUtils.CheckNotNull(cipherKey, "cipherKey"); // Decrypt the encrypted key RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.Key = cipherKey; // Decrypt each of the encrypted data elements using the decrypted key foreach (XmlElement encryptedDataElem in encryptedDataElems) { // Decrypt the data byte[] decryptedData = XmlSecurityUtils.Decrypt(encryptedDataElem, sessionKey); XmlDocument containerDoc = encryptedDataElem.OwnerDocument; // Replace the encrypted data with the decrypted data within the container EncryptedXml encryptedXml = new EncryptedXml(containerDoc); encryptedXml.ReplaceData(encryptedDataElem, decryptedData); } }
public static void ReplaceData2(this EncryptedXml encryptedXml, XmlElement inputElement, byte[] decryptedData) { if (inputElement == null) { throw new ArgumentNullException("inputElement"); } if (decryptedData == null) { throw new ArgumentNullException("decryptedData"); } XmlNode parent = inputElement.ParentNode; if (parent.NodeType == XmlNodeType.Document) { // We're replacing the root element, so we need to // 1. Import the decrypted data into an XmlNode // 2. Get that node into the target document // 3. Replace the root element with the decrypted node XmlDocument importDocument = new XmlDocument(); importDocument.LoadXml(encryptedXml.Encoding.GetString(decryptedData)); XmlNode importedNode = inputElement.OwnerDocument.ImportNode(importDocument.DocumentElement, true); parent.RemoveChild(inputElement); parent.AppendChild(importedNode); } else { // We're not replacing the root, so the built-in ReplaceData API will work for this input // node. encryptedXml.ReplaceData(inputElement, decryptedData); } }
public static void Decrypt(XmlDocument Doc, SymmetricAlgorithm Alg) { XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; // If the EncryptedData element was not found, throw an exception. if (encryptedElement == null) { throw new XmlException("The EncryptedData element was not found."); } // Create an EncryptedData object and populate it. EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(); // Decrypt the element using the symmetric key. byte[] rgbOutput = exml.DecryptData(edElement, Alg); // Replace the encryptedData element with the plaintext XML element. exml.ReplaceData(encryptedElement, rgbOutput); }
protected override void DecryptElement(XmlElement element, string password) { var saltXmlAttribute = XmlHelpers.GetAttributeNode(element, "Salt"); if (string.IsNullOrEmpty(saltXmlAttribute?.Value)) { throw new InvalidXmlException($"Encrypted node {element.Name} does not contain required Attribute \"Salt\"", element); } byte[] rgbSalt; try { rgbSalt = Convert.FromBase64String(saltXmlAttribute.Value); } catch (FormatException) { throw new InvalidXmlException($"Invalid value of Attribute \"Salt\" ({saltXmlAttribute.Value}) in encrypted node {element.Name} ", element); } var ivXmlAttribute = XmlHelpers.GetAttributeNode(element, "IV"); if (string.IsNullOrEmpty(ivXmlAttribute?.Value)) { throw new InvalidXmlException($"Encrypted node {element.Name} does not contain required Attribute \"IV\"", element); } byte[] numArray; try { numArray = Convert.FromBase64String(ivXmlAttribute.Value); } catch (FormatException) { throw new InvalidXmlException($"Invalid value of Attribute \"IV\" ({ivXmlAttribute.Value}) in encrypted node {element.Name} ", element); } var cryptoServiceProvider = new TripleDESCryptoServiceProvider { IV = numArray }; var passwordDeriveBytes = new PasswordDeriveBytes(password, rgbSalt); var encryptedData = new EncryptedData(); encryptedData.LoadXml(element); cryptoServiceProvider.Key = passwordDeriveBytes.CryptDeriveKey("TripleDES", "SHA1", 192, cryptoServiceProvider.IV); // weird edge case - if this is a parameter value, then it must replace one more parent level up var elementToReplace = element.ParentNode?.Name == "DTS:Property" && (element.ParentNode as XmlElement) != null && element.ParentNode?.ParentNode?.Name == "DTS:PackageParameter" ? (XmlElement)element.ParentNode : element; var exml = new EncryptedXml(); try { var output = exml.DecryptData(encryptedData, cryptoServiceProvider); exml.ReplaceData(elementToReplace, output); } catch (CryptographicException) { throw new InvalidPaswordException(); } }
public void Decrypt(string xmlFileName) { TripleDESCryptoServiceProvider encryptionKey = new TripleDESCryptoServiceProvider(); encryptionKey.Key = UTF8Encoding.UTF8.GetBytes(""); // your salt value XmlDocument document = new XmlDocument(); document.Load(xmlFileName); XmlElement encOrderElem = document.GetElementsByTagName("EncryptedData")[0] as XmlElement; EncryptedData encData = new EncryptedData(); encData.LoadXml(encOrderElem); EncryptedXml encryptedXml = new EncryptedXml(); byte[] decryptedOrder = encryptedXml.DecryptData(encData, encryptionKey); encryptedXml.ReplaceData(encOrderElem, decryptedOrder); document.Save(xmlFileName); }
/// <summary> /// Расшифровывает ответ ФСС по пути /// </summary> /// <param name="filename">Путь к зашифрованному файлу</param> /// <returns>Путь к расшифрованному файлу</returns> public string decryptResponse(string filename) { if (!File.Exists(filename)) { throw new Exception("Шаг 5. Файл не найден!\r\nПуть:" + filename); } string filename5 = filename + ".decrypted.xml"; // Создаем объект XmlDocument. XmlDocument xmlDoc = new XmlDocument(); // Загружаем XML файл в объект XmlDocument. xmlDoc.PreserveWhitespace = true; xmlDoc.Load(filename); // Ищем все зашифрованные данные. XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); nsmgr.AddNamespace("xenc", "http://www.w3.org/2001/04/xmlenc#"); XmlNodeList list = xmlDoc.SelectNodes("//xenc:EncryptedData", nsmgr); // Создаем объект EncryptedXml. EncryptedXml exml = new EncryptedXml(xmlDoc); if (list != null) { // Для всех зашифрованных данных. foreach (XmlNode node in list) { XmlElement element = node as XmlElement; EncryptedData encryptedData = new EncryptedData(); encryptedData.LoadXml(element); // Находим подходящий ключ для расшифрования. SymmetricAlgorithm decryptionKey = GetDecryptionKey(exml, encryptedData); if (decryptionKey == null) { throw new Exception("Ключ для расшифрования сообщения не найден"); } // И на нем расшифровываем данные. byte[] decryptedData = exml.DecryptData(encryptedData, decryptionKey); exml.ReplaceData(element, decryptedData); } } xmlDoc.Save(filename5); // Отображаем файл если требуется для дебага if (DEBUG_STEP < 5) { foView view = new foView(); view.Text = filename5; view.xmlFileName = filename5; view.Show(); } return(filename5); }
public void ReplaceData_XmlElementNull() { EncryptedXml ex = new EncryptedXml(); ex.ReplaceData(null, new byte[0]); }
public void ReplaceData_XmlElementNull() { EncryptedXml ex = new EncryptedXml(); Assert.Throws <ArgumentNullException>(() => ex.ReplaceData(null, new byte[0])); }
public void RoundtripSample1() { using (StringWriter sw = new StringWriter()) { // Encryption { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml("<root> <child>sample</child> </root>"); XmlElement body = doc.DocumentElement; using (Aes aes = Aes.Create()) { aes.Mode = CipherMode.CBC; aes.KeySize = 256; aes.IV = Convert.FromBase64String("pBUM5P03rZ6AE4ZK5EyBrw=="); aes.Key = Convert.FromBase64String("o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640="); aes.Padding = PaddingMode.Zeros; EncryptedXml exml = new EncryptedXml(); byte[] encrypted = exml.EncryptData(body, aes, false); EncryptedData edata = new EncryptedData(); edata.Type = EncryptedXml.XmlEncElementUrl; edata.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); EncryptedKey ekey = new EncryptedKey(); // omit key encryption, here for testing byte[] encKeyBytes = aes.Key; ekey.CipherData = new CipherData(encKeyBytes); ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); DataReference dr = new DataReference(); dr.Uri = "_0"; ekey.AddReference(dr); edata.KeyInfo.AddClause(new KeyInfoEncryptedKey(ekey)); edata.KeyInfo = new KeyInfo(); ekey.KeyInfo.AddClause(new RSAKeyValue(RSA.Create())); edata.CipherData.CipherValue = encrypted; EncryptedXml.ReplaceElement(doc.DocumentElement, edata, false); doc.Save(new XmlTextWriter(sw)); } } // Decryption { using (Aes aes = Aes.Create()) { aes.Mode = CipherMode.CBC; aes.KeySize = 256; aes.Key = Convert.FromBase64String( "o/ilseZu+keLBBWGGPlUHweqxIPc4gzZEFWr2nBt640="); aes.Padding = PaddingMode.Zeros; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(sw.ToString()); EncryptedXml encxml = new EncryptedXml(doc); EncryptedData edata = new EncryptedData(); edata.LoadXml(doc.DocumentElement); encxml.ReplaceData(doc.DocumentElement, encxml.DecryptData(edata, aes)); } } } }
/// <summary> /// Decrypts a list of elements. /// </summary> /// <param name="encryptedKeyElems">List of encrypted key elements.</param> /// <param name="encryptedDataElems">List of encrypted data elements.</param> /// <param name="certificate">Certificate to use for key decryption.</param> public void Decrypt(IList <XmlElement> encryptedKeyElems, IList <XmlElement> encryptedDataElems, X509Certificate2 certificate) { ArgumentUtils.CheckNotNullNorEmpty(encryptedKeyElems, "encryptedKeyElems"); ArgumentUtils.CheckNotNullNorEmpty(encryptedDataElems, "encryptedDataElems"); ArgumentUtils.CheckNotNull(certificate, "certificate"); // Check the certificate has a private key if (certificate.PrivateKey == null) { throw new XspException("Certificate with subject '" + certificate.Subject + "' does not contain a private key"); } XmlDocument containerDoc = encryptedKeyElems[0].OwnerDocument; // Check the 'encryptedKeyElems' elements foreach (XmlElement encryptedKeyElem in encryptedKeyElems) { // Check they are all 'xenc:EncryptedKey' elements if (!XmlUtils.CheckElement(encryptedKeyElem, EncryptedKeyTag, EncryptedXml.XmlEncNamespaceUrl)) { throw new XspException("Element within the keys list is not " + "an 'xenc:EncryptedKey'"); } // Check they all belong to the same document if (encryptedKeyElem.OwnerDocument != containerDoc) { throw new XspException("All 'xenc:EncryptedKey' elements " + "must belong to the same document"); } } // Check the 'encryptedDataElems' elements foreach (XmlElement encryptedDataElem in encryptedDataElems) { // Check they are all 'xenc:EncryptedData' elements if (!XmlUtils.CheckElement(encryptedDataElem, EncryptedDataTag, EncryptedXml.XmlEncNamespaceUrl)) { throw new XspException("Element within the encrypted data list is " + "not an 'xenc:EncryptedData' element."); } // Check they all belong to the same document if (encryptedDataElem.OwnerDocument != containerDoc) { throw new XspException("All 'xenc:EncryptedData' elements " + "must belong to the same document"); } } // Attempt to find the matching encrypted key for the certificate EncryptedKey encryptedKey = null; foreach (XmlElement encryptedKeyElem in encryptedKeyElems) { EncryptedKey currentEncryptedKey = new EncryptedKey(); currentEncryptedKey.LoadXml(encryptedKeyElem); // Check if the subject key identifier specified within the // 'KeyInfo' of the encrypted key matches the certificate if (MatchesCertificate(currentEncryptedKey, certificate)) { encryptedKey = currentEncryptedKey; break; } } // Check if a key was found if (encryptedKey == null) { throw new KeyMismatchException( "Could not find a matching encrypted key for certificate '" + certificate.Subject + "'."); } // Decrypt the encrypted key RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.Key = XmlSecurityUtils.DecryptEncryptedKey( encryptedKey, certificate.PrivateKey); // Decrypt each of the encrypted data elements using the decrypted key foreach (XmlElement encryptedDataElem in encryptedDataElems) { // Decrypt the data byte[] decryptedData = XmlSecurityUtils.Decrypt( encryptedDataElem, sessionKey); // Replace the encrypted data with the decrypted data within the container EncryptedXml encryptedXml = new EncryptedXml(containerDoc); encryptedXml.ReplaceData(encryptedDataElem, decryptedData); } }
internal static ICollection <SamlAttributesEncryptionKey> DecryptXml(RSA asymmetricAlgorithm, XmlDocument xmlDoc, string[] xmlElementsXPaths) { if (asymmetricAlgorithm == null) { throw new ArgumentNullException("asymmetricAlgorithm"); } if (xmlDoc == null) { throw new ArgumentNullException("xmlDoc"); } if (xmlElementsXPaths == null) { throw new ArgumentNullException("xmlElementsXPaths"); } // create the symmetric algorithm which was used for encryption var symmetricAlgorithm = new AesManaged(); symmetricAlgorithm.Padding = PaddingMode.ISO10126; ICollection <SamlAttributesEncryptionKey> attributesEncryptionKeys = new Collection <SamlAttributesEncryptionKey>(); foreach (var xPath in xmlElementsXPaths) { // select all encrypted attribute elements var encryptedElements = xmlDoc.SelectNodes(xPath); Debug.Assert(encryptedElements != null, "encryptedElements != null"); foreach (XmlNode encryptedElement in encryptedElements) { // load the encrypted data element var encryptedDataElement = encryptedElement.SelectSingleNode("//*[local-name() = 'EncryptedData']") as XmlElement; var encryptedData = new EncryptedData(); Debug.Assert(encryptedDataElement != null, "encryptedDataElement != null"); encryptedData.LoadXml(encryptedDataElement); // load the encrypted key element var encryptedKeyElement = encryptedDataElement.SelectSingleNode("//*[local-name() = 'EncryptedKey']") as XmlElement; var encryptedKey = new EncryptedKey(); Debug.Assert(encryptedKeyElement != null, "encryptedKeyElement != null"); encryptedKey.LoadXml(encryptedKeyElement); // decrypt the key using the specifief asymmetric algorithm var symetricKey = asymmetricAlgorithm.Decrypt(encryptedKey.CipherData.CipherValue, RSAEncryptionPadding.OaepSHA1); // use the asymmetric decrypted key to decrypt the encrypted data using the specified symmetric algorithm symmetricAlgorithm.Key = symetricKey; var output = new EncryptedXml { Mode = CipherMode.CBC, Padding = PaddingMode.ISO10126 }; var data = output.DecryptData(encryptedData, symmetricAlgorithm); var previousSibling = (XmlElement)encryptedElement.PreviousSibling; var nextSibling = (XmlElement)encryptedElement.NextSibling; var parentElement = (XmlElement)encryptedElement.ParentNode; // replace the encrypted element with its decrypted form output.ReplaceData((XmlElement)encryptedElement, data); var currentNode = previousSibling?.NextSibling ?? nextSibling?.PreviousSibling ?? parentElement?.FirstChild; if (currentNode == null) { continue; } var attributesEncryptionKey = GetAttributesEncryptionKey(currentNode, symetricKey); if (attributesEncryptionKey != null) { attributesEncryptionKeys.Add(attributesEncryptionKey); } } } return(attributesEncryptionKeys); }