void AssertDecryption1 (string filename) { XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; doc.Load (filename); EncryptedXml encxml = new EncryptedXml (doc); RSACryptoServiceProvider rsa = new X509Certificate2 ("Test/System.Security.Cryptography.Xml/sample.pfx", "mono").PrivateKey as RSACryptoServiceProvider; 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, true); Rijndael aes = new RijndaelManaged (); 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)); } }
/// <summary> /// Decrypts the specified XML element. /// </summary> /// <param name="encryptedElement">An encrypted XML element.</param> /// <returns>The decrypted form of <paramref name="encryptedElement"/>.</returns> /// <remarks> public XElement Decrypt(XElement encryptedElement) { if (encryptedElement == null) { throw new ArgumentNullException(nameof(encryptedElement)); } // <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#"> // ... // </EncryptedData> // EncryptedXml works with XmlDocument, not XLinq. When we perform the conversion // we'll wrap the incoming element in a dummy <root /> element since encrypted XML // doesn't handle encrypting the root element all that well. var xmlDocument = new XmlDocument(); xmlDocument.Load(new XElement("root", encryptedElement).CreateReader()); var elementToDecrypt = (XmlElement)xmlDocument.DocumentElement.FirstChild; // Perform the decryption and update the document in-place. var encryptedXml = new EncryptedXml(xmlDocument); _decryptor.PerformPreDecryptionSetup(encryptedXml); encryptedXml.DecryptDocument(); // Strip the <root /> element back off and convert the XmlDocument to an XElement. return XElement.Load(xmlDocument.DocumentElement.FirstChild.CreateNavigator().ReadSubtree()); }
internal static void Encrypt(this XmlElement elementToEncrypt, bool useOaep, X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); var encryptedData = new EncryptedData { Type = EncryptedXml.XmlEncElementUrl, EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url) }; var algorithm = useOaep ? EncryptedXml.XmlEncRSAOAEPUrl : EncryptedXml.XmlEncRSA15Url; var encryptedKey = new EncryptedKey { EncryptionMethod = new EncryptionMethod(algorithm), }; var encryptedXml = new EncryptedXml(); byte[] encryptedElement; using (var symmetricAlgorithm = new RijndaelManaged()) { symmetricAlgorithm.KeySize = 256; encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(symmetricAlgorithm.Key, (RSA)certificate.PublicKey.Key, useOaep)); encryptedElement = encryptedXml.EncryptData(elementToEncrypt, symmetricAlgorithm, false); } encryptedData.CipherData.CipherValue = encryptedElement; encryptedData.KeyInfo = new KeyInfo(); encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey)); EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false); }
public XmlDecryptionTransform () { Algorithm = XmlSignature.AlgorithmNamespaces.XmlDecryptionTransform; encryptedXml = new EncryptedXml (); exceptUris = new ArrayList (); lockObject = new object (); }
/// <summary> /// Decrypt data with X509 certificate /// </summary> /// <param name="encryptedNode"></param> /// <returns></returns> public override System.Xml.XmlNode Decrypt(System.Xml.XmlNode encryptedNode) { XmlDocument doc = encryptedNode.OwnerDocument; EncryptedXml eXml = new EncryptedXml(doc); eXml.DecryptDocument(); return doc.DocumentElement; }
/// <summary> /// 解密数据. /// </summary> /// <param name="Doc"></param> /// <param name="Alg"></param> public 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; // 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 void Decrypt(XmlDocument document, X509Certificate2 encryptionCert) { var assertion = document.FindChild(EncryptedAssertion); if (assertion == null) return; // Not encrypted, shame on them. var data = document.EncryptedChild("EncryptedData"); var keyElement = assertion.EncryptedChild("EncryptedKey"); var encryptedData = new EncryptedData(); encryptedData.LoadXml(data); var encryptedKey = new EncryptedKey(); encryptedKey.LoadXml(keyElement); var encryptedXml = new EncryptedXml(document); // Get encryption secret key used by decrypting with the encryption certificate's private key var secretKey = GetSecretKey(encryptedKey, encryptionCert.PrivateKey); // Seed the decryption algorithm with secret key and then decrypt var algorithm = GetSymmetricBlockEncryptionAlgorithm(encryptedData.EncryptionMethod.KeyAlgorithm); algorithm.Key = secretKey; var decryptedBytes = encryptedXml.DecryptData(encryptedData, algorithm); // Put decrypted xml elements back into the document in place of the encrypted data encryptedXml.ReplaceData(assertion, decryptedBytes); }
public static void DecryptElement(XmlElement encryptedElement, string password) { RijndaelWrapper wrapper = new RijndaelWrapper(password); EncryptedData data = new EncryptedData(); data.LoadXml(encryptedElement); EncryptedXml result = new EncryptedXml(); byte[] decrypted = result.DecryptData(data, wrapper.SymmetricAlgorithm); result.ReplaceData(encryptedElement, decrypted); }
/// <summary> /// 解密Xml。 /// </summary> /// <param name="doc"></param> public static void DecryptorXml(XmlDocument doc) { if (doc != null) { EncryptedXml encXml = new EncryptedXml(doc); encXml.AddKeyNameMapping("session", keyAlgorithm); encXml.DecryptDocument(); } }
/// <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 static void Encrypt(XmlDocument Doc, string ElementToEncrypt, AsymmetricAlgorithm publicKey) { XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement; EncryptedXml eXml = new EncryptedXml(); eXml.AddKeyNameMapping("encKey", publicKey); EncryptedData edElement = eXml.Encrypt(elementToEncrypt, "encKey"); EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); }
/// <summary> /// Encrypt data with X509 certificate /// </summary> /// <param name="node"></param> /// <returns></returns> public override System.Xml.XmlNode Encrypt(System.Xml.XmlNode node) { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(node.OuterXml); EncryptedXml eXml = new EncryptedXml(); EncryptedData eData = eXml.Encrypt(doc.DocumentElement, cert); return eData.GetXml(); }
public override XmlNode Encrypt(XmlNode node) { XmlDocument xmlDocument; EncryptedXml exml; byte[] rgbOutput; EncryptedData ed; KeyInfoName kin; SymmetricAlgorithm symAlg; EncryptedKey ek; KeyInfoEncryptedKey kek; XmlElement inputElement; RSACryptoServiceProvider rsa = GetCryptoServiceProvider(false, false); // Encrypt the node with the new key xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; xmlDocument.LoadXml("<foo>"+ node.OuterXml+ "</foo>"); exml = new EncryptedXml(xmlDocument); inputElement = xmlDocument.DocumentElement; // Create a new 3DES key symAlg = new TripleDESCryptoServiceProvider(); byte[] rgbKey1 = GetRandomKey(); symAlg.Key = rgbKey1; symAlg.Mode = CipherMode.ECB; symAlg.Padding = PaddingMode.PKCS7; rgbOutput = exml.EncryptData(inputElement, symAlg, true); ed = new EncryptedData(); ed.Type = EncryptedXml.XmlEncElementUrl; ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl); ed.KeyInfo = new KeyInfo(); ek = new EncryptedKey(); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); ek.KeyInfo = new KeyInfo(); ek.CipherData = new CipherData(); ek.CipherData.CipherValue = EncryptedXml.EncryptKey(symAlg.Key, rsa, UseOAEP); kin = new KeyInfoName(); kin.Value = _KeyName; ek.KeyInfo.AddClause(kin); kek = new KeyInfoEncryptedKey(ek); ed.KeyInfo.AddClause(kek); ed.CipherData = new CipherData(); ed.CipherData.CipherValue = rgbOutput; EncryptedXml.ReplaceElement(inputElement, ed, true); // Get node from the document foreach (XmlNode node2 in xmlDocument.ChildNodes) if (node2.NodeType == XmlNodeType.Element) foreach (XmlNode node3 in node2.ChildNodes) // node2 is the "foo" node if (node3.NodeType == XmlNodeType.Element) return node3; // node3 is the "EncryptedData" node return null; }
/// <summary> /// 加密Xml。 /// </summary> /// <param name="doc"></param> public static void EncryptorXml(XmlDocument doc) { if (doc != null) { XmlElement encElement = doc.DocumentElement; EncryptedXml encXml = new EncryptedXml(doc); encXml.AddKeyNameMapping("session", keyAlgorithm); EncryptedData encData = encXml.Encrypt(encElement, "session"); EncryptedXml.ReplaceElement(encElement, encData, false); } }
public override XmlNode Decrypt(XmlNode encryptedNode) { // Load config section to encrypt into xmlDocument instance XmlDocument doc = encryptedNode.OwnerDocument; EncryptedXml eXml = new EncryptedXml(doc); // Add a key-name mapping. This method can only decrypt documents that present the specified key name. eXml.AddKeyNameMapping(this.keyName, this.rsaKey); eXml.DecryptDocument(); return doc.DocumentElement; }
/// <summary> /// /// </summary> /// <param name="element"></param> /// <param name="password"></param> /// <param name="content">true to replace content, false to replace entire element</param> public static void EncryptElement(XmlElement element, string password, bool content) { XmlDocument doc = element.OwnerDocument; EncryptedXml eXml = new EncryptedXml(doc); RijndaelWrapper wrapper = new RijndaelWrapper(password); byte[] cipherText = eXml.EncryptData((XmlElement)doc.FirstChild.FirstChild, wrapper.SymmetricAlgorithm, content); EncryptedData data = new EncryptedData(); data.EncryptionMethod = new EncryptionMethod(wrapper.Url); data.CipherData = new CipherData(cipherText); data.KeyInfo = new KeyInfo(); EncryptedXml.ReplaceElement(element, data, content); }
public override XmlNode Decrypt(XmlNode encryptedNode) { XmlDocument document = new XmlDocument(); EncryptedXml xml = null; RSACryptoServiceProvider cryptoServiceProvider = this.GetCryptoServiceProvider(false, true); document.PreserveWhitespace = true; document.LoadXml(encryptedNode.OuterXml); xml = new EncryptedXml(document); xml.AddKeyNameMapping(this._KeyName, cryptoServiceProvider); xml.DecryptDocument(); cryptoServiceProvider.Clear(); return document.DocumentElement; }
private static EncryptedData ToEncryptedData(EncryptedXml encryptedXml, XmlElement element, RijndaelManaged key) { var encryptedElement = encryptedXml.EncryptData(element, key, false); var encryptedData = new EncryptedData { Type = EncryptedXml.XmlEncElementUrl, EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES128Url), Id = null, CipherData = new CipherData(encryptedElement) }; return encryptedData; }
public override XmlNode Decrypt (XmlNode encrypted_node) { XmlDocument doc = new ConfigurationXmlDocument (); doc.Load (new StringReader (encrypted_node.OuterXml)); EncryptedXml ex = new EncryptedXml (doc); ex.AddKeyNameMapping ("Rsa Key", GetProvider ()); ex.DecryptDocument (); return doc.DocumentElement; }
public override XmlNode Decrypt(XmlNode encryptedNode) { XmlDocument xmlDocument = new XmlDocument(); EncryptedXml exml = null; RSACryptoServiceProvider rsa = GetCryptoServiceProvider(false, true); xmlDocument.PreserveWhitespace = true; xmlDocument.LoadXml(encryptedNode.OuterXml); exml = new EncryptedXml(xmlDocument); exml.AddKeyNameMapping(_KeyName, rsa); exml.DecryptDocument(); rsa.Clear(); return xmlDocument.DocumentElement; }
public override XmlNode Encrypt(XmlNode node) { RSACryptoServiceProvider cryptoServiceProvider = this.GetCryptoServiceProvider(false, false); XmlDocument document = new XmlDocument { PreserveWhitespace = true }; document.LoadXml("<foo>" + node.OuterXml + "</foo>"); EncryptedXml xml = new EncryptedXml(document); XmlElement documentElement = document.DocumentElement; SymmetricAlgorithm symmetricAlgorithm = new TripleDESCryptoServiceProvider(); byte[] randomKey = this.GetRandomKey(); symmetricAlgorithm.Key = randomKey; symmetricAlgorithm.Mode = CipherMode.ECB; symmetricAlgorithm.Padding = PaddingMode.PKCS7; byte[] buffer = xml.EncryptData(documentElement, symmetricAlgorithm, true); EncryptedData encryptedData = new EncryptedData { Type = "http://www.w3.org/2001/04/xmlenc#Element", EncryptionMethod = new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#tripledes-cbc"), KeyInfo = new KeyInfo() }; EncryptedKey encryptedKey = new EncryptedKey { EncryptionMethod = new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#rsa-1_5"), KeyInfo = new KeyInfo(), CipherData = new CipherData() }; encryptedKey.CipherData.CipherValue = EncryptedXml.EncryptKey(symmetricAlgorithm.Key, cryptoServiceProvider, this.UseOAEP); KeyInfoName clause = new KeyInfoName { Value = this._KeyName }; encryptedKey.KeyInfo.AddClause(clause); KeyInfoEncryptedKey key2 = new KeyInfoEncryptedKey(encryptedKey); encryptedData.KeyInfo.AddClause(key2); encryptedData.CipherData = new CipherData(); encryptedData.CipherData.CipherValue = buffer; EncryptedXml.ReplaceElement(documentElement, encryptedData, true); foreach (XmlNode node2 in document.ChildNodes) { if (node2.NodeType == XmlNodeType.Element) { foreach (XmlNode node3 in node2.ChildNodes) { if (node3.NodeType == XmlNodeType.Element) { return node3; } } } } return null; }
public static void Encryptwsmd(XmlDocument Doc, SymmetricAlgorithm Key) { if (Doc == null) { throw new ArgumentNullException("Doc"); } string name = "WSMD"; if (Key == null) { throw new ArgumentNullException("Alg"); } XmlElement inputElement = Doc.GetElementsByTagName(name)[0] as XmlElement; if (inputElement == null) { throw new XmlException("The specified element was not found"); } byte[] buffer = new EncryptedXml().EncryptData(inputElement, Key, false); EncryptedData encryptedData = new EncryptedData(); encryptedData.Type = "http://www.w3.org/2001/04/xmlenc#Element"; string algorithm = null; if (Key is TripleDES) { algorithm = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"; } else if (Key is DES) { algorithm = "http://www.w3.org/2001/04/xmlenc#des-cbc"; } if (!(Key is Rijndael)) { throw new CryptographicException("The specified algorithm is notsupported for XML Encryption."); } switch (Key.KeySize) { case 0x80: algorithm = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; break; case 0xc0: algorithm = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"; break; case 0x100: algorithm = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"; break; } encryptedData.EncryptionMethod = new EncryptionMethod(algorithm); encryptedData.CipherData.CipherValue = buffer; EncryptedXml.ReplaceElement(inputElement, encryptedData, false); }
public void LoadKeyValuePairsFromValidEncryptedXml() { var xml = @" <settings> <Data.Setting> <DefaultConnection> <Connection.String>Test.Connection.String</Connection.String> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <ConnectionString>AnotherTestConnectionString</ConnectionString> <Provider>MySql</Provider> </Inventory> </Data.Setting> </settings>"; // This AES key will be used to encrypt the 'Inventory' element var aes = Aes.Create(); aes.KeySize = 128; aes.GenerateKey(); // Perform the encryption var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); var encryptedXml = new EncryptedXml(xmlDocument); encryptedXml.AddKeyNameMapping("myKey", aes); var elementToEncrypt = (XmlElement)xmlDocument.SelectSingleNode("//Inventory"); EncryptedXml.ReplaceElement(elementToEncrypt, encryptedXml.Encrypt(elementToEncrypt, "myKey"), content: false); // Quick sanity check: the document should no longer contain an 'Inventory' element Assert.Null(xmlDocument.SelectSingleNode("//Inventory")); // Arrange var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath, new EncryptedXmlDocumentDecryptor(doc => { var innerEncryptedXml = new EncryptedXml(doc); innerEncryptedXml.AddKeyNameMapping("myKey", aes); return innerEncryptedXml; })); // Act xmlConfigSrc.Load(StringToStream(xmlDocument.OuterXml)); // Assert Assert.Equal("Test.Connection.String", xmlConfigSrc.Get("DATA.SETTING:DEFAULTCONNECTION:CONNECTION.STRING")); Assert.Equal("SqlClient", xmlConfigSrc.Get("DATA.SETTING:DefaultConnection:Provider")); Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("data.setting:inventory:connectionstring")); Assert.Equal("MySql", xmlConfigSrc.Get("Data.setting:Inventory:Provider")); }
internal static XmlDocument GetPlainAsertion(SecurityTokenResolver securityTokenResolver, XmlElement el) { var encryptedDataElement = GetElement(HttpRedirectBindingConstants.EncryptedData, Saml20Constants.Xenc, el); var encryptedData = new System.Security.Cryptography.Xml.EncryptedData(); encryptedData.LoadXml(encryptedDataElement); var encryptedKey = new System.Security.Cryptography.Xml.EncryptedKey(); var encryptedKeyElement = GetElement(HttpRedirectBindingConstants.EncryptedKey, Saml20Constants.Xenc, el); encryptedKey.LoadXml(encryptedKeyElement); var securityKeyIdentifier = new SecurityKeyIdentifier(); foreach (KeyInfoX509Data v in encryptedKey.KeyInfo) { foreach (X509Certificate2 cert in v.Certificates) { var cl = new X509RawDataKeyIdentifierClause(cert); securityKeyIdentifier.Add(cl); } } var clause = new EncryptedKeyIdentifierClause(encryptedKey.CipherData.CipherValue, encryptedKey.EncryptionMethod.KeyAlgorithm, securityKeyIdentifier); SecurityKey key; var success = securityTokenResolver.TryResolveSecurityKey(clause, out key); if (!success) { throw new InvalidOperationException("Cannot locate security key"); } SymmetricSecurityKey symmetricSecurityKey = key as SymmetricSecurityKey; if (symmetricSecurityKey == null) { throw new InvalidOperationException("Key must be symmentric key"); } SymmetricAlgorithm symmetricAlgorithm = symmetricSecurityKey.GetSymmetricAlgorithm(encryptedData.EncryptionMethod.KeyAlgorithm); var encryptedXml = new System.Security.Cryptography.Xml.EncryptedXml(); var plaintext = encryptedXml.DecryptData(encryptedData, symmetricAlgorithm); var assertion = new XmlDocument { PreserveWhitespace = true }; assertion.Load(new StringReader(Encoding.UTF8.GetString(plaintext))); return(assertion); }
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)); }
/// <summary> /// Permite desencriptar con una llave privada un documento XML encriptado con una clave pública /// </summary> /// <param name="xmlIn"></param> /// <param name="privateKey"></param> /// <returns></returns> public static XmlDocument DecryptXml(XmlDocument xmlIn, RSA privateKey) { const string keyName = "Llave"; if ((xmlIn == null)) { throw new ArgumentNullException("xmlIn"); } if ((privateKey == null)) { throw new ArgumentNullException("privateKey"); } var exml = new EncryptedXml(xmlIn); exml.AddKeyNameMapping(keyName, privateKey); exml.DecryptDocument(); return xmlIn; }
public void GenerateEncryptedAssertion_01() { XmlDocument assertion = AssertionUtil.GetTestAssertion_01(); // Create an EncryptedData instance to hold the results of the encryption.o EncryptedData encryptedData = new EncryptedData(); encryptedData.Type = EncryptedXml.XmlEncElementUrl; encryptedData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Create a symmetric key. RijndaelManaged aes = new RijndaelManaged(); aes.KeySize = 256; aes.GenerateKey(); // Encrypt the assertion and add it to the encryptedData instance. EncryptedXml encryptedXml = new EncryptedXml(); byte[] encryptedElement = encryptedXml.EncryptData(assertion.DocumentElement, aes, false); encryptedData.CipherData.CipherValue = encryptedElement; // Add an encrypted version of the key used. encryptedData.KeyInfo = new KeyInfo(); EncryptedKey encryptedKey = new EncryptedKey(); // Use this certificate to encrypt the key. X509Certificate2 cert = new X509Certificate2(@"Saml20\Certificates\sts_dev_certificate.pfx", "test1234"); RSA publicKeyRSA = cert.PublicKey.Key as RSA; Assert.IsNotNull(publicKeyRSA, "Public key of certificate was not an RSA key. Modify test."); encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(aes.Key, publicKeyRSA, false)); encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey)); // Create the resulting Xml-document to hook into. EncryptedAssertion encryptedAssertion = new EncryptedAssertion(); encryptedAssertion.encryptedData = new saml20.Schema.XEnc.EncryptedData(); encryptedAssertion.encryptedKey = new saml20.Schema.XEnc.EncryptedKey[1]; encryptedAssertion.encryptedKey[0] = new saml20.Schema.XEnc.EncryptedKey(); XmlDocument result; result = Serialization.Serialize(encryptedAssertion); XmlElement encryptedDataElement = GetElement(dk.nita.saml20.Schema.XEnc.EncryptedData.ELEMENT_NAME, Saml20Constants.XENC, result); EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false); }
public static void Encrypt(XmlDocument Doc, string ElementName, System.Security.Cryptography.SymmetricAlgorithm Key) { XmlElement inputElement = Doc.GetElementsByTagName(ElementName)[0] as XmlElement; EncryptedXml encryptedXml = new EncryptedXml(); byte[] cipherValue = encryptedXml.EncryptData(inputElement, Key, false); EncryptedData encryptedData = new EncryptedData(); encryptedData.Type = "http://www.w3.org/2001/04/xmlenc#Element"; string algorithm = null; if (Key is System.Security.Cryptography.TripleDES) { algorithm = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"; } else { if (Key is System.Security.Cryptography.DES) { algorithm = "http://www.w3.org/2001/04/xmlenc#des-cbc"; } } if (Key is System.Security.Cryptography.Rijndael) { int keySize = Key.KeySize; if (keySize != 128) { if (keySize != 192) { if (keySize == 256) { algorithm = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"; } } else { algorithm = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"; } } else { algorithm = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; } } encryptedData.EncryptionMethod = new EncryptionMethod(algorithm); encryptedData.CipherData.CipherValue = cipherValue; EncryptedXml.ReplaceElement(inputElement, encryptedData, false); }
public override XmlNode Encrypt(XmlNode node) { // Load config section to encrypt into xmlDocument instance XmlDocument doc = new XmlDocument { PreserveWhitespace = true }; doc.LoadXml(node.OuterXml); // Create Rijndael key. RijndaelManaged sessionKey = new RijndaelManaged(); sessionKey.KeySize = 256; EncryptedXml eXml = new EncryptedXml(); XmlElement elementToEncrypt = (XmlElement)node; byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false); EncryptedData edElement = new EncryptedData(); edElement.Type = EncryptedXml.XmlEncElementUrl; edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Encrypt the session key and add it to an EncryptedKey element. EncryptedKey ek = new EncryptedKey(); byte[] encryptedKey = EncryptedXml.EncryptKey(sessionKey.Key, this.rsaKey, false); ek.CipherData = new CipherData(encryptedKey); ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url); // Set the KeyInfo element to specify the name of the RSA key. edElement.KeyInfo = new KeyInfo(); KeyInfoName kin = new KeyInfoName(); kin.Value = this.keyName; // Add the KeyInfoName element to the // EncryptedKey object. ek.KeyInfo.AddClause(kin); edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek)); // Add the encrypted element data to the // EncryptedData object. edElement.CipherData.CipherValue = encryptedElement; // EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false); return edElement.GetXml(); }
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 string EncryptAssertion(string assertionXml, bool useOaep = false, X509Certificate2 certificate = null) { if (certificate == null) { certificate = TestCert2; } var xmlDoc = new XmlDocument { PreserveWhitespace = true }; var wrappedAssertion = string.Format(@"<saml2:EncryptedAssertion xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion"">{0}</saml2:EncryptedAssertion>", assertionXml); xmlDoc.LoadXml(wrappedAssertion); var symmetricAlgorithm = new RijndaelManaged { KeySize = 256 }; var encryptedData = new EncryptedData { Type = EncryptedXml.XmlEncElementUrl, EncryptionMethod = new System.Security.Cryptography.Xml.EncryptionMethod(EncryptedXml.XmlEncAES256Url) }; var elementToEncrypt = (XmlElement) xmlDoc.GetElementsByTagName("Assertion", Saml2Namespaces.Saml2Name)[0]; // Encrypt the assertion and add it to the encryptedData instance. var encryptedXml = new EncryptedXml(); var encryptedElement = encryptedXml.EncryptData(elementToEncrypt, symmetricAlgorithm, false); encryptedData.CipherData.CipherValue = encryptedElement; // Add an encrypted version of the key used. encryptedData.KeyInfo = new KeyInfo(); var algorithm = useOaep ? EncryptedXml.XmlEncRSAOAEPUrl : EncryptedXml.XmlEncRSA15Url; var encryptedKey = new EncryptedKey { EncryptionMethod = new System.Security.Cryptography.Xml.EncryptionMethod(algorithm), CipherData = new CipherData(EncryptedXml.EncryptKey(symmetricAlgorithm.Key, (RSA)certificate.PublicKey.Key, useOaep)) }; encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey)); EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false); return xmlDoc.OuterXml; }
// Try to decrypt the EncryptedKey given the key mapping public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) { if (encryptedKey is null) { throw new ArgumentNullException(nameof(encryptedKey)); } if (encryptedKey.KeyInfo == null) { return(null); } IEnumerator keyInfoEnum = encryptedKey.KeyInfo.GetEnumerator(); KeyInfoName kiName; KeyInfoX509Data kiX509Data; KeyInfoRetrievalMethod kiRetrievalMethod; KeyInfoEncryptedKey kiEncKey; EncryptedKey ek; bool fOAEP; while (keyInfoEnum.MoveNext()) { kiName = keyInfoEnum.Current as KeyInfoName; if (kiName != null) { // Get the decryption key from the key mapping string keyName = kiName.Value; object kek = _keyNameMapping[keyName]; if (kek != null) { if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); } // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table if (kek is SymmetricAlgorithm) { return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)kek)); } // kek is an RSA key: get fOAEP from the algorithm, default to false fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)kek, fOAEP)); } break; } kiX509Data = keyInfoEnum.Current as KeyInfoX509Data; if (kiX509Data != null) { X509Certificate2Collection collection = Utils.BuildBagOfCerts(kiX509Data, CertUsageType.Decryption); foreach (X509Certificate2 certificate in collection) { using (RSA privateKey = certificate.GetRSAPrivateKey()) { if (privateKey != null) { if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); } fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, fOAEP)); } } } break; } kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod; if (kiRetrievalMethod != null) { string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri); ek = new EncryptedKey(); ek.LoadXml(GetIdElement(_document, idref)); try { //Following checks if XML dsig processing is in loop and within the limit defined by machine // admin or developer. Once the recursion depth crosses the defined limit it will throw exception. _xmlDsigSearchDepthCounter++; if (IsOverXmlDsigRecursionLimit()) { //Throw exception once recursion limit is hit. throw new CryptoSignedXmlRecursionException(); } else { return(DecryptEncryptedKey(ek)); } } finally { _xmlDsigSearchDepthCounter--; } } kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey; if (kiEncKey != null) { ek = kiEncKey.EncryptedKey; // recursively process EncryptedKey elements byte[] encryptionKey = DecryptEncryptedKey(ek); if (encryptionKey != null) { // this is a symmetric algorithm for sure SymmetricAlgorithm symAlg = CryptoHelpers.CreateFromName <SymmetricAlgorithm>(encryptedKey.EncryptionMethod.KeyAlgorithm); if (symAlg == null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); } symAlg.Key = encryptionKey; if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null) { throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm); } symAlg.Key = encryptionKey; return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, symAlg)); } } } return(null); }
// Encrypts the given element with the key name specified. A corresponding key name mapping // has to be defined before calling this method. The key name is added as // a KeyNameInfo KeyInfo to an EncryptedKey (AES session key) generated randomly. public EncryptedData Encrypt(XmlElement inputElement, string keyName) { if (inputElement is null) { throw new ArgumentNullException(nameof(inputElement)); } if (keyName is null) { throw new ArgumentNullException(nameof(keyName)); } object encryptionKey = null; if (_keyNameMapping != null) { encryptionKey = _keyNameMapping[keyName]; } if (encryptionKey == null) { throw new CryptographicException(SR.Cryptography_Xml_MissingEncryptionKey); } // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table SymmetricAlgorithm symKey = encryptionKey as SymmetricAlgorithm; RSA rsa = encryptionKey as RSA; // Create the EncryptedData object, using an AES-256 session key by default. EncryptedData ed = new EncryptedData(); ed.Type = EncryptedXml.XmlEncElementUrl; ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url); // Include the key name in the EncryptedKey KeyInfo. string encryptionMethod = null; if (symKey == null) { encryptionMethod = EncryptedXml.XmlEncRSA15Url; } else if (symKey is TripleDES) { // CMS Triple DES Key Wrap encryptionMethod = EncryptedXml.XmlEncTripleDESKeyWrapUrl; } #pragma warning disable SYSLIB0022 // Rijndael types are obsolete else if (symKey is Rijndael || symKey is Aes) #pragma warning restore SYSLIB0022 { // FIPS AES Key Wrap switch (symKey.KeySize) { case 128: encryptionMethod = EncryptedXml.XmlEncAES128KeyWrapUrl; break; case 192: encryptionMethod = EncryptedXml.XmlEncAES192KeyWrapUrl; break; case 256: encryptionMethod = EncryptedXml.XmlEncAES256KeyWrapUrl; break; } } else { // throw an exception if the transform is not in the previous categories throw new CryptographicException(SR.Cryptography_Xml_NotSupportedCryptographicTransform); } EncryptedKey ek = new EncryptedKey(); ek.EncryptionMethod = new EncryptionMethod(encryptionMethod); ek.KeyInfo.AddClause(new KeyInfoName(keyName)); // Create a random AES session key and encrypt it with the public key associated with the certificate. using (Aes aes = Aes.Create()) { ek.CipherData.CipherValue = (symKey == null ? EncryptedXml.EncryptKey(aes.Key, rsa, false) : EncryptedXml.EncryptKey(aes.Key, symKey)); // Encrypt the input element with the random session key that we've created above. KeyInfoEncryptedKey kek = new KeyInfoEncryptedKey(ek); ed.KeyInfo.AddClause(kek); ed.CipherData.CipherValue = EncryptData(inputElement, aes, false); } return(ed); }