public static void Decrypt(XmlDocument Doc, RSA Alg, string KeyName) { // Verificare argumente if (Doc == null) { throw new ArgumentNullException("Doc"); } if (Alg == null) { throw new ArgumentNullException("Alg"); } if (KeyName == null) { throw new ArgumentNullException("KeyName"); } // Se creeaza un nou obiect de tip EncryptedXml. EncryptedXml exml = new EncryptedXml(Doc); // Se adauga o mapare numeCheie - algoritm exml.AddKeyNameMapping(KeyName, Alg); // Se decripteaza exml.DecryptDocument(); }
public void DecryptData_CipherReference_InvalidUri() { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; string xml = "<root> <child>sample</child> </root>"; doc.LoadXml(xml); var random = new SecureRandom(); var ivdata = new byte[128 / 8]; var keydata = new byte[256 / 8]; random.NextBytes(ivdata); random.NextBytes(keydata); var param = new ParametersWithIV(new KeyParameter(keydata), ivdata); EncryptedXml exml = new EncryptedXml(); exml.AddKeyNameMapping("aes", param); EncryptedData ed = exml.Encrypt(doc.DocumentElement, "aes"); ed.CipherData = new CipherData(); ed.CipherData.CipherReference = new CipherReference("invaliduri"); // https://github.com/dotnet/corefx/issues/19272 Action decrypt = () => exml.DecryptData(ed, param); Assert.Throws <System.Security.Cryptography.CryptographicException>(decrypt); }
public void DecryptEncryptedKey_KeyInfoEncryptedKey() { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; string xml = "<root> <child>sample</child> </root>"; doc.LoadXml(xml); var random = new SecureRandom(); var keydata = new byte[256 / 8]; random.NextBytes(keydata); var param = new KeyParameter(keydata); keydata = new byte[128 / 8]; random.NextBytes(keydata); var innerParam = new KeyParameter(keydata); keydata = new byte[192 / 8]; random.NextBytes(keydata); var outerParam = new KeyParameter(keydata); EncryptedXml exml = new EncryptedXml(doc); exml.AddKeyNameMapping("aes", param); EncryptedKey ekey = new EncryptedKey(); byte[] encKeyBytes = EncryptedXml.EncryptKey(outerParam.GetKey(), param); ekey.CipherData = new CipherData(encKeyBytes); ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); ekey.Id = "Key_ID"; ekey.KeyInfo = new KeyInfo(); ekey.KeyInfo.AddClause(new KeyInfoName("aes")); KeyInfo topLevelKeyInfo = new KeyInfo(); topLevelKeyInfo.AddClause(new KeyInfoEncryptedKey(ekey)); EncryptedKey ekeyTopLevel = new EncryptedKey(); byte[] encTopKeyBytes = EncryptedXml.EncryptKey(innerParam.GetKey(), outerParam); ekeyTopLevel.CipherData = new CipherData(encTopKeyBytes); ekeyTopLevel.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); ekeyTopLevel.KeyInfo = topLevelKeyInfo; doc.LoadXml(ekeyTopLevel.GetXml().OuterXml); byte[] decryptedKey = exml.DecryptEncryptedKey(ekeyTopLevel); Assert.Equal(innerParam.GetKey(), decryptedKey); EncryptedData eData = new EncryptedData(); eData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); eData.KeyInfo = topLevelKeyInfo; var decryptedAlg = exml.GetDecryptionKey(eData, null); Assert.Equal(outerParam.GetKey(), ((KeyParameter)decryptedAlg).GetKey()); }
public void Encrypt_DecryptDocument_AES() { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; string xml = "<root> <child>sample</child> </root>"; doc.LoadXml(xml); var aes = CipherUtilities.GetCipher("AES/CBC/ZEROBYTEPADDING"); var random = new SecureRandom(); var ivdata = new byte[128 / 8]; var keydata = new byte[256 / 8]; random.NextBytes(ivdata); random.NextBytes(keydata); var param = new ParametersWithIV(new KeyParameter(keydata), ivdata); EncryptedXml exml = new EncryptedXml(); exml.AddKeyNameMapping("aes", param); EncryptedData ed = exml.Encrypt(doc.DocumentElement, "aes"); doc.LoadXml(ed.GetXml().OuterXml); EncryptedXml exmlDecryptor = new EncryptedXml(doc); exmlDecryptor.AddKeyNameMapping("aes", param); exmlDecryptor.DecryptDocument(); Assert.Equal(xml, doc.OuterXml); }
/// <summary> /// Decrypts all EncryptedData elements of the XML document that were specified /// during initialization of the System.Security.Cryptography.Xml.EncryptedXml class. /// </summary> /// <param name="document">The xml document containing the element to decrypt.</param> /// <param name="algorithm">The symmetric alogorithm used to decrypt the element.</param> /// <param name="keyName">The name to map to keyObject.</param> public static void Decrypt(XmlDocument document, SymmetricAlgorithm algorithm, string keyName) { // Check the arguments. if (document == null) { throw new ArgumentNullException("document"); } if (string.IsNullOrEmpty(keyName)) { throw new ArgumentNullException("keyName"); } if (document == null) { throw new ArgumentNullException("algorithm"); } // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(document); // Add a key-name mapping. // This method can only decrypt documents // that present the specified key name. exml.AddKeyNameMapping(keyName, algorithm); // Decrypt the element. exml.DecryptDocument(); }
public void Decrypt(X509Certificate2 certificate, bool useFakeKeyName) { if (useFakeKeyName) { KeyInfoName keyInfoName = new KeyInfoName(kkKey); XmlNodeList encryptedKeyNodes = docValue.GetElementsByTagName("EncryptedKey"); XmlNode encryptedKeyNode = encryptedKeyNodes.Item(0); XmlNode referenceNode = encryptedKeyNode.FirstChild; XmlElement infoElement = docValue.CreateElement(null, "KeyInfo", "http://www.w3.org/2000/09/xmldsig#"); XmlElement keyNameElement = docValue.CreateElement(null, "KeyName", "http://www.w3.org/2000/09/xmldsig#"); keyNameElement.InnerText = kkKey; infoElement.AppendChild(keyNameElement); encryptedKeyNode.InsertAfter(infoElement, referenceNode); encryptedKeyNode.ParentNode.AppendChild(encryptedKeyNode); } EncryptedXml exml = new EncryptedXml(docValue); RSACryptoServiceProvider privateKeyProvider = (RSACryptoServiceProvider)certificate.PrivateKey; exml.AddKeyNameMapping(kkKey, privateKeyProvider); exml.DecryptDocument(); }
public static void Decrypt(XmlDocument Doc, RSA Alg, string KeyName) { try { // Check the arguments. if (Doc == null) throw new ArgumentNullException("Doc"); if (Alg == null) throw new ArgumentNullException("Alg"); if (KeyName == null) throw new ArgumentNullException("KeyName"); // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(Doc); // Add a key-name mapping. // This method can only decrypt documents // that present the specified key name. exml.AddKeyNameMapping(KeyName, Alg); // Decrypt the element. exml.DecryptDocument(); } catch (Exception ex) { AutoClosingMessageBox.Show("Sorry!! License is not Valid."); } }
static void decipher(string filename, XmlDocument xmlDoc, List <RSA> Keys) { // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(xmlDoc); // Add a key-name mapping. // This method can only decrypt documents // that present the specified key name. int keyid = 0; foreach (RSA Alg in Keys) { try { exml.ClearKeyNameMappings(); Trace.WriteLine("Trying to decrypt with keyid " + keyid++); exml.AddKeyNameMapping("rsaKey", Alg); // Decrypt the element. exml.DecryptDocument(); return; } catch (Exception ex) { Trace.WriteLine("When decoding the document - trying next key: " + ex.Message); } } Trace.WriteLine("The program tried to use " + keyid + " keys"); throw new PingCastleDataException(filename, "Unable to find a key in the configuration which can decrypt the document"); }
public static void Decrypt(XmlDocument Doc, AsymmetricAlgorithm privateKey) { EncryptedXml exml = new EncryptedXml(Doc); exml.AddKeyNameMapping("encKey", privateKey); exml.DecryptDocument(); }
public XmlElement DecryptSingleElementByKeyNumber(int encryptedKeyNumber) { EncryptedKey encryptedKey = new EncryptedKey(); encryptedKey.LoadXml((XmlElement)this._encryptedKeyElements[encryptedKeyNumber]); ReferenceList referenceList = encryptedKey.ReferenceList; EncryptedReference encryptedReference = referenceList.Item(0); string uri = encryptedReference.Uri; KeyInfo keyInfo = encryptedKey.KeyInfo; this._referenceList.Clear(); ArrayList referenceElementList = new ArrayList(); referenceElementList = this.FindXmlElementByURI(uri, this._tempdocument.ChildNodes[1]); XmlElement keyInfoElement = this._tempdocument.CreateElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl); keyInfoElement.AppendChild(_tempdocument.ImportNode((XmlNode)encryptedKey.GetXml(), true)); XmlElement encryptedDataElement = (XmlElement)referenceElementList[0]; RSACryptoServiceProvider provider = this._webService.RSACryptoServiceProvider; EncryptedXml encXml = new EncryptedXml(this._tempdocument); encXml.AddKeyNameMapping("Web Service Public Key", provider); EncryptedData data = new EncryptedData(); data.LoadXml((XmlElement)encryptedDataElement); SymmetricAlgorithm algo = SymmetricAlgorithm.Create(); algo.Key = encXml.DecryptEncryptedKey(encryptedKey); byte[] t = encXml.DecryptData(data, algo); encXml.ReplaceData(encryptedDataElement, t); this._tempdocument.GetElementsByTagName("wsse:Security")[0].RemoveChild(_tempdocument.GetElementsByTagName("xenc:EncryptedKey")[0]); XmlElement root = (XmlElement)this._decryptedDataList[encryptedKeyNumber]; return((XmlElement)root); }
private static void Decrypt(XmlDocument doc, SymmetricAlgorithm key, string keyName) { var encrypted = new EncryptedXml(doc); encrypted.AddKeyNameMapping(keyName, key); encrypted.DecryptDocument(); }
// Encrypts the XML file public void Encrypt(string filePath) { if (filePath == null) { throw new ArgumentNullException("Doc"); } else { XmlDoc.Load(filePath); } EncryptedXml eXml = new EncryptedXml(); eXml.AddKeyNameMapping(KeyName, Alg); // Find all of the xml elements within the file XmlElement root = XmlDoc.DocumentElement; XmlNodeList nodes = root.SelectNodes("//*"); foreach (XmlElement elementToEncrypt in nodes) { EncryptedData edElement = eXml.Encrypt(elementToEncrypt, KeyName); EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); } // If you do not save the file then the encryption is not saved XmlDoc.Save(filePath); // Save the key so the file can be read next time ACE is launched saveKey(); }
public bool Decrypt(string filePath) { bool error; if (filePath == null) { throw new ArgumentNullException("Doc"); } else { XmlDoc.Load(filePath); } if (File.Exists(GetKeyFile())) { loadKey(); // this will execute successfully even if the file was not encrypted EncryptedXml exml = new EncryptedXml(XmlDoc); exml.AddKeyNameMapping(KeyName, Alg); exml.DecryptDocument(); // If you do not save the file then the encryption is not saved XmlDoc.Save(filePath); error = false; } else { error = true; } return(error); }
/// <summary> /// Método para descriptografia /// </summary> /// <param name="doc">arquivo XML</param> /// <param name="alg">RSA</param> /// <param name="keyName">chave</param> public static void Decrypt(XmlDocument doc, RSA alg, string keyName) { // Check the arguments. if (doc == null) { throw new ArgumentNullException("doc"); } if (alg == null) { throw new ArgumentNullException("alg"); } if (keyName == null) { throw new ArgumentNullException("keyName"); } // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(doc); // Add a key-name mapping. // This method can only decrypt documents // that present the specified key name. exml.AddKeyNameMapping(keyName, alg); // Decrypt the element. exml.DecryptDocument(); }
public static SmtpAddress Decrypt(XmlElement encryptedSharingKey, SymmetricSecurityKey symmetricSecurityKey) { XmlDocument xmlDocument = new SafeXmlDocument(); try { xmlDocument.AppendChild(xmlDocument.ImportNode(encryptedSharingKey, true)); } catch (XmlException) { SharingKeyHandler.Tracer.TraceError <string>(0L, "Unable to import XML element of sharing key: {0}", encryptedSharingKey.OuterXml); return(SmtpAddress.Empty); } EncryptedXml encryptedXml = new EncryptedXml(xmlDocument); encryptedXml.AddKeyNameMapping("key", symmetricSecurityKey.GetSymmetricAlgorithm("http://www.w3.org/2001/04/xmlenc#tripledes-cbc")); try { encryptedXml.DecryptDocument(); } catch (CryptographicException) { SharingKeyHandler.Tracer.TraceError <string>(0L, "Unable to decrypt XML element sharing key: {0}", encryptedSharingKey.OuterXml); return(SmtpAddress.Empty); } return(new SmtpAddress(xmlDocument.DocumentElement.InnerText)); }
public static void Decrypt(XmlDocument Doc, SymmetricAlgorithm Alg, string KeyName) { // Check the arguments. if (Doc == null) { throw new ArgumentNullException("Doc"); } if (Alg == null) { throw new ArgumentNullException("Alg"); } if (KeyName == null) { throw new ArgumentNullException("KeyName"); } // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(Doc); // Add the key name mapping. exml.AddKeyNameMapping(KeyName, Alg); // Decrypt the XML document. exml.DecryptDocument(); }
/// <summary> /// Decrypts the specified XML element. /// </summary> /// <param name="encryptedElement"> /// An encrypted XML element. /// </param> /// <returns> /// The decrypted form of <paramref name="encryptedElement" />. /// </returns> /// <exception cref="System.ArgumentNullException"> /// Thrown if <paramref name="encryptedElement" /> is <see langword="null" />. /// </exception> public XElement Decrypt(XElement encryptedElement) { if (encryptedElement == null) { throw new ArgumentNullException(nameof(encryptedElement)); } this.Logger.LogDebug("Decrypting XML with certificate {0}.", this._keyName); // Create a faux XML document from the XElement so we can use EncryptedXml. var xmlDocument = encryptedElement.ToXmlDocumentWithRootNode(); // Do the actual decryption. Algorithm based on MSDN docs: // https://msdn.microsoft.com/en-us/library/ms229746(v=vs.110).aspx var encryptedXml = new EncryptedXml(xmlDocument); encryptedXml.AddKeyNameMapping(this._keyName, this._keyProvider); try { encryptedXml.DecryptDocument(); } catch (CryptographicException ex) when(ex.Message.IndexOf("bad key", StringComparison.OrdinalIgnoreCase) >= 0) { // If you get a CryptographicException with the message "Bad Key" // in it here, it means the certificate used to encrypt wasn't generated // with "-sky Exchange" in makecert.exe so the encrypt/decrypt functionality // isn't enabled for it. this.Logger.LogError("Bad key exception was encountered. Did you generate the certificate with '-sky Exchange' to enable encryption/decryption?"); throw; } return(xmlDocument.ElementToProcess().ToXElement()); }
//<SNIPPET1> public static void Decrypt(XmlDocument Doc, RSA Alg, string KeyName) { // Check the arguments. if (Doc == null) { throw new ArgumentNullException("Doc"); } if (Alg == null) { throw new ArgumentNullException("Alg"); } if (KeyName == null) { throw new ArgumentNullException("KeyName"); } // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(Doc); // Add a key-name mapping. // This method can only decrypt documents // that present the specified key name. exml.AddKeyNameMapping(KeyName, Alg); while (Doc.GetElementsByTagName("EncryptedData", EncryptedXml.XmlEncNamespaceUrl).Count > 0) { // Decrypt the element. exml.DecryptDocument(); } }
public void PropagatedNamespaces_XmlDecryptionTransform(bool addPropagatedNamespace, string expectedResult) { XmlDocument baseDocument = new XmlDocument(); baseDocument.LoadXml("<a><b><c xmlns=\"urn:foo\"/></b></a>"); var aes = CipherUtilities.GetCipher("AES/CBC/PKCS7"); var random = new SecureRandom(); var keyData = new byte[aes.GetBlockSize()]; var ivData = new byte[aes.GetBlockSize()]; random.NextBytes(ivData); random.NextBytes(keyData); var key = new ParametersWithIV(new KeyParameter(keyData), ivData); EncryptedXml encryptedXml = new EncryptedXml(baseDocument); encryptedXml.AddKeyNameMapping("key", key); XmlElement bElement = (XmlElement)baseDocument.DocumentElement.SelectSingleNode("b"); EncryptedData encryptedData = encryptedXml.Encrypt(bElement, "key"); EncryptedXml.ReplaceElement(bElement, encryptedData, false); XmlDecryptionTransform decryptionTransform = new XmlDecryptionTransform(); decryptionTransform.EncryptedXml = encryptedXml; decryptionTransform.LoadInput(baseDocument); if (addPropagatedNamespace) { decryptionTransform.PropagatedNamespaces.Add("f", "urn:foo"); } XmlDocument decryptedDocument = (XmlDocument)decryptionTransform.GetOutput(typeof(XmlDocument)); Assert.Equal(expectedResult, decryptedDocument.OuterXml); }
public static XmlDocument Decrypt(XmlDocument Doc, string KeyName) { CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_ENC_RSA_KEY"; RSA Alg = new RSACryptoServiceProvider(cspParams); // Check the arguments. if (Doc == null) { throw new ArgumentNullException("Doc"); } if (KeyName == null) { throw new ArgumentNullException("KeyName"); } // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(Doc); // Add a key-name mapping. // This method can only decrypt documents // that present the specified key name. exml.AddKeyNameMapping(KeyName, Alg); // Decrypt the element. exml.DecryptDocument(); return(Doc); }
private XmlDocument CreateDocumentFromSecrets(IEnumerable <Secret> secrets) { XmlDocument document = CreateNewDocument(); if (secrets == null) { return(document); } // Check if there are any elements in the collection, and also get hold of the first element in the collection IEnumerator <Secret> enumerator = secrets.GetEnumerator(); if (!enumerator.MoveNext()) { if (New <ILogging>().IsWarningEnabled) { New <ILogging>().LogWarning($"{nameof(CreateDocumentFromSecrets)} No elements in collection"); } return(document); } // This is where we sort the secret collection into a session per key.... Right now we assume the same // key for all.... InternalEncryptionKey key = new InternalEncryptionKey(enumerator.Current.EncryptionKey); // Get some salt for the key-derivation function byte[] salt = New <IRandomGenerator>().Generate(16); SymmetricAlgorithm masterKey = DeriveMasterKey(key.DecryptPassphrase(), salt, _defaultRfc2898iterations); LastUpdateUtc = New <INow>().Utc; // Start building a session node, recording the used salt and the number of iterations XmlElement xecretsSession = document.CreateElement("XecretsSession"); xecretsSession.Attributes.Append(document.CreateAttribute("KeyDerivation")).Value = "Rfc2898"; xecretsSession.Attributes.Append(document.CreateAttribute("Salt")).Value = System.Convert.ToBase64String(salt); xecretsSession.Attributes.Append(document.CreateAttribute("Iterations")).Value = _defaultRfc2898iterations.ToString(CultureInfo.InvariantCulture); xecretsSession.Attributes.Append(document.CreateAttribute("LastUpdateUtc")).Value = LastUpdateUtc.ToString(CultureInfo.InvariantCulture); // Get the secrets collection in the form of an appropriate XML Element, suitable for encryption. XmlElement secretsElement = CreateSecretsElement(document, secrets); xecretsSession.AppendChild(secretsElement); // Encrypt the node, creating a named session key and embedding it in the output. EncryptedXml encryptedXml = new EncryptedXml(); encryptedXml.AddKeyNameMapping(KEYNAME, masterKey); EncryptedData encryptedData = encryptedXml.Encrypt(secretsElement, KEYNAME); // Replace the encrypted element with the encrypted same EncryptedXml.ReplaceElement(secretsElement, encryptedData, false); // Finally, actually append this to the set of sessions. document.SelectSingleNode("AxantumXecrets/XecretsSessions").AppendChild(xecretsSession); return(document); }
public static void Decrypt(XmlDocument doc, RsaKeyParameters rsaKey, string keyName) { var encrypted = new EncryptedXml(doc); encrypted.AddKeyNameMapping(keyName, rsaKey); encrypted.DecryptDocument(); }
private static void Decrypt(XmlDocument doc, RSA rsaKey, string keyName) { var encrypted = new EncryptedXml(doc); encrypted.AddKeyNameMapping(keyName, rsaKey); encrypted.DecryptDocument(); }
public void GetDecryptionKey_CarriedKeyName() { using (Aes aes = Aes.Create()) using (Aes innerAes = Aes.Create()) { innerAes.KeySize = 128; EncryptedData edata = new EncryptedData(); edata.KeyInfo = new KeyInfo(); edata.KeyInfo.AddClause(new KeyInfoName("aes")); EncryptedKey ekey = new EncryptedKey(); byte[] encKeyBytes = EncryptedXml.EncryptKey(innerAes.Key, aes); ekey.CipherData = new CipherData(encKeyBytes); ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); ekey.CarriedKeyName = "aes"; ekey.KeyInfo = new KeyInfo(); ekey.KeyInfo.AddClause(new KeyInfoName("another_aes")); XmlDocument doc = new XmlDocument(); doc.LoadXml(ekey.GetXml().OuterXml); EncryptedXml exml = new EncryptedXml(doc); exml.AddKeyNameMapping("another_aes", aes); SymmetricAlgorithm decryptedAlg = exml.GetDecryptionKey(edata, EncryptedXml.XmlEncAES256Url); Assert.Equal(innerAes.Key, decryptedAlg.Key); } }
public static void Decrypt(XmlDocument Doc, RSA Alg, string KeyName) { ////////////////////////////////////////////////////////////////////// // Check the arguments // if (Doc == null) { throw new ArgumentNullException("Doc"); } if (Alg == null) { throw new ArgumentNullException("Alg"); } if (KeyName == null) { throw new ArgumentNullException("KeyName"); } ////////////////////////////////////////////////////////////////////// // Create a new EncryptedXml object to decrypt data // EncryptedXml exml = new EncryptedXml(Doc); // Add a key-name mapping. // This method can only decrypt documents // that present the specified key name. exml.AddKeyNameMapping(KeyName, Alg); // Decrypt the element. exml.DecryptDocument(); }
public void DecryptData_CipherReference_InvalidUri() { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; string xml = "<root> <child>sample</child> </root>"; doc.LoadXml(xml); using (Aes aes = Aes.Create()) { EncryptedXml exml = new EncryptedXml(); exml.AddKeyNameMapping("aes", aes); EncryptedData ed = exml.Encrypt(doc.DocumentElement, "aes"); ed.CipherData = new CipherData(); ed.CipherData.CipherReference = new CipherReference("invaliduri"); // https://github.com/dotnet/corefx/issues/19272 Action decrypt = () => exml.DecryptData(ed, aes); if (PlatformDetection.IsFullFramework) { Assert.Throws <ArgumentNullException>(decrypt); } else { Assert.Throws <CryptographicException>(decrypt); } } }
public void PropagatedNamespaces_XmlDecryptionTransform(bool addPropagatedNamespace, string expectedResult) { XmlDocument baseDocument = new XmlDocument(); baseDocument.LoadXml("<a><b><c xmlns=\"urn:foo\"/></b></a>"); using (Aes aes = Aes.Create()) { EncryptedXml encryptedXml = new EncryptedXml(baseDocument); encryptedXml.AddKeyNameMapping("key", aes); XmlElement bElement = (XmlElement)baseDocument.DocumentElement.SelectSingleNode("b"); EncryptedData encryptedData = encryptedXml.Encrypt(bElement, "key"); EncryptedXml.ReplaceElement(bElement, encryptedData, false); XmlDecryptionTransform decryptionTransform = new XmlDecryptionTransform(); decryptionTransform.EncryptedXml = encryptedXml; decryptionTransform.LoadInput(baseDocument); if (addPropagatedNamespace) { decryptionTransform.PropagatedNamespaces.Add("f", "urn:foo"); } XmlDocument decryptedDocument = (XmlDocument)decryptionTransform.GetOutput(typeof(XmlDocument)); Assert.Equal(expectedResult, decryptedDocument.OuterXml); } }
private XmlDocument GetTransformedOutput(XmlDocument doc, string nodeToEncrypt) { var aes = CipherUtilities.GetCipher("AES/CBC/PKCS7"); var random = new SecureRandom(); var keyData = new byte[aes.GetBlockSize()]; var ivData = new byte[aes.GetBlockSize()]; random.NextBytes(ivData); random.NextBytes(keyData); var key = new ParametersWithIV(new KeyParameter(keyData), ivData); var encryptedXml = new EncryptedXml(); encryptedXml.AddKeyNameMapping("aes", key); XmlElement elementToEncrypt = (XmlElement)doc.DocumentElement.SelectSingleNode(nodeToEncrypt); EncryptedData encryptedData = encryptedXml.Encrypt(elementToEncrypt, "aes"); EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(doc.NameTable); xmlNamespaceManager.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); XmlElement encryptedNode = (XmlElement)doc.DocumentElement.SelectSingleNode("//enc:EncryptedData", xmlNamespaceManager); encryptedNode.SetAttribute("ID", "#_0"); transform.LoadInput(doc); transform.EncryptedXml = encryptedXml; XmlDocument transformedDocument = (XmlDocument)transform.GetOutput(); transform.EncryptedXml = null; return(transformedDocument); }
private static void Decrypt(SymmetricAlgorithm key, XmlDocument xmlDoc) { var encryptedXml = new EncryptedXml(xmlDoc); encryptedXml.AddKeyNameMapping("MyKey", key); encryptedXml.DecryptDocument(); }
public XDocument Decrypt() { EncryptedXml exml = new EncryptedXml(xmlDoc); exml.AddKeyNameMapping(KeyName, rsaKey); exml.DecryptDocument(); return(xmlDoc.ToXDocument()); }