private void DecryptDocument(X509Certificate2 decryptionSertificate) { var encryptedNode = ResponseDocument.SelectSingleNode("/env:Envelope/env:Body/xenc:EncryptedData", Nsmgr) as XmlElement; if (encryptedNode == null) return; var encryptedXml = new EncryptedXml(ResponseDocument); var encryptedData = new EncryptedData(); encryptedData.LoadXml(encryptedNode); var privateKey = decryptionSertificate.PrivateKey as RSACryptoServiceProvider; var cipher = ResponseDocument.SelectSingleNode("/env:Envelope/env:Header/wsse:Security/xenc:EncryptedKey/xenc:CipherData/xenc:CipherValue", Nsmgr).InnerText; AesManaged aes = new AesManaged { Mode = CipherMode.CBC, KeySize = 256, Padding = PaddingMode.None, Key = privateKey.Decrypt(Convert.FromBase64String(cipher), true) }; encryptedXml.ReplaceData(encryptedNode, encryptedXml.DecryptData(encryptedData, aes)); }
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); }
/// <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); }
private static XmlDocument DecryptXmlDocument(XmlDocument encryptedXmlDocument) { // Создание объекта для дешифрации XML var encryptedXml = new GostEncryptedXml(encryptedXmlDocument); var nsManager = new XmlNamespaceManager(encryptedXmlDocument.NameTable); nsManager.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); // Поиск всех зашифрованных XML-элементов var encryptedDataList = encryptedXmlDocument.SelectNodes("//enc:EncryptedData", nsManager); if (encryptedDataList != null) { foreach (XmlElement encryptedData in encryptedDataList) { // Загрузка элемента EncryptedData var elementEncryptedData = new EncryptedData(); elementEncryptedData.LoadXml(encryptedData); // Извлечение симметричный ключ для расшифровки элемента EncryptedData var sessionKey = GetDecryptionKey(elementEncryptedData); if (sessionKey != null) { // Расшифровка элемента EncryptedData var decryptedData = encryptedXml.DecryptData(elementEncryptedData, sessionKey); // Замена элемента EncryptedData его расшифрованным представлением encryptedXml.ReplaceData(encryptedData, decryptedData); } } } return encryptedXmlDocument; }
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)); } }
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> /// 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. }
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)); }
static void Main(string[] args) { byte[] bytes = System.Text.Encoding.Unicode.GetBytes(args[0]); System.Security.Cryptography.RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged(); rijndaelManaged.Key = bytes; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; xmlDocument.Load("needfiles"); XmlElement xmlElement = xmlDocument.GetElementsByTagName("EncryptedData")[0] as XmlElement; EncryptedData encryptedData = new EncryptedData(); encryptedData.LoadXml(xmlElement); EncryptedXml encryptedXml = new EncryptedXml(); byte[] decryptedData = encryptedXml.DecryptData(encryptedData, rijndaelManaged); encryptedXml.ReplaceData(xmlElement, decryptedData); if (rijndaelManaged != null) { rijndaelManaged.Clear(); } Console.WriteLine(xmlDocument.OuterXml); }
public void DecryptDocument() { XmlNamespaceManager nsmgr = new XmlNamespaceManager(this.m_document.NameTable); nsmgr.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#"); XmlNodeList list = this.m_document.SelectNodes("//enc:EncryptedData", nsmgr); if (list != null) { foreach (XmlNode node in list) { XmlElement element = node as XmlElement; EncryptedData encryptedData = new EncryptedData(); encryptedData.LoadXml(element); SymmetricAlgorithm decryptionKey = this.GetDecryptionKey(encryptedData, null); if (decryptionKey == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingDecryptionKey")); } byte[] decryptedData = this.DecryptData(encryptedData, decryptionKey); this.ReplaceData(element, decryptedData); } } }
// decrypts the document using the defined key mapping in GetDecryptionKey // The behaviour of this method can be extended because GetDecryptionKey is virtual // the document is decrypted in place public void DecryptDocument () { // Look for all EncryptedData elements and decrypt them XmlNamespaceManager nsm = new XmlNamespaceManager(m_document.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); XmlNodeList encryptedDataList = m_document.SelectNodes("//enc:EncryptedData", nsm); if (encryptedDataList != null) { foreach (XmlNode encryptedDataNode in encryptedDataList) { XmlElement encryptedDataElement = encryptedDataNode as XmlElement; EncryptedData ed = new EncryptedData(); ed.LoadXml(encryptedDataElement); SymmetricAlgorithm symAlg = GetDecryptionKey(ed, null); if (symAlg == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingDecryptionKey")); byte[] decrypted = DecryptData(ed, symAlg); ReplaceData(encryptedDataElement, decrypted); } } }
public void DecryptDocument () { XmlNodeList nodes = document.GetElementsByTagName ("EncryptedData", XmlEncNamespaceUrl); foreach (XmlNode node in nodes) { EncryptedData encryptedData = new EncryptedData (); encryptedData.LoadXml ((XmlElement) node); SymmetricAlgorithm symAlg = GetDecryptionKey (encryptedData, encryptedData.EncryptionMethod.KeyAlgorithm); ReplaceData ((XmlElement) node, DecryptData (encryptedData, symAlg)); } }
public override object GetOutput () { XmlDocument document; if (inputObj is Stream) { document = new XmlDocument (); document.PreserveWhitespace = true; document.XmlResolver = GetResolver (); document.Load (new XmlSignatureStreamReader ( new StreamReader (inputObj as Stream))); } else if (inputObj is XmlDocument) { document = inputObj as XmlDocument; } else throw new NullReferenceException (); XmlNodeList nodes = document.GetElementsByTagName ("EncryptedData", EncryptedXml.XmlEncNamespaceUrl); foreach (XmlNode node in nodes) { if (node == document.DocumentElement && exceptUris.Contains ("#xpointer(/)")) break; // Need to exclude based on ExceptURI. Only accept #id references. foreach (string uri in exceptUris) if (IsTargetElement ((XmlElement) node, uri.Substring (1))) break; EncryptedData encryptedData = new EncryptedData (); encryptedData.LoadXml ((XmlElement) node); SymmetricAlgorithm symAlg = EncryptedXml.GetDecryptionKey (encryptedData, encryptedData.EncryptionMethod.KeyAlgorithm); EncryptedXml.ReplaceData ((XmlElement) node, EncryptedXml.DecryptData (encryptedData, symAlg)); } return document; }
//解密 private void btnJieMi_Click(object sender, EventArgs e) { try { RijndaelManaged key = new RijndaelManaged(); key.IV = keyIv; key.Key = keyKey; XmlDocument Doc = new XmlDocument(); Doc.PreserveWhitespace = true; Doc.Load(this.label1.Text); XmlElement encryptedElement = Doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; if (encryptedElement == null) { throw new XmlException("T错误!"); } EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); EncryptedXml exml = new EncryptedXml();//利用它解密 byte[] rgbOutput = exml.DecryptData(edElement, key);//利用解药解密 exml.ReplaceData(encryptedElement, rgbOutput);//替换密文部分 Doc.Save(this.label1.Text); succes(); } catch (Exception ex) { fail(); } }
XmlElement VerifyInput2 (MessageBuffer buf) { Message msg2 = buf.CreateMessage (); StringWriter sw = new StringWriter (); using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (sw))) { msg2.WriteMessage (w); } XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; doc.LoadXml (sw.ToString ()); // decrypt the key with service certificate privkey PaddingMode mode = PaddingMode.PKCS7; // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None. EncryptedXml encXml = new EncryptedXml (doc); encXml.Padding = mode; X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test.pfx", "mono"); XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable); nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope"); nsmgr.AddNamespace ("c", "http://schemas.xmlsoap.org/ws/2005/02/sc"); nsmgr.AddNamespace ("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); nsmgr.AddNamespace ("e", "http://www.w3.org/2001/04/xmlenc#"); nsmgr.AddNamespace ("dsig", "http://www.w3.org/2000/09/xmldsig#"); XmlNode n = doc.SelectSingleNode ("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr); Assert.IsNotNull (n, "premise: enckey does not exist"); string raw = n.InnerText; byte [] rawbytes = Convert.FromBase64String (raw); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) cert2.PrivateKey; byte [] decryptedKey = EncryptedXml.DecryptKey (rawbytes, rsa, true);//rsa.Decrypt (rawbytes, true); #if false // create derived keys Dictionary<string,byte[]> keys = new Dictionary<string,byte[]> (); InMemorySymmetricSecurityKey skey = new InMemorySymmetricSecurityKey (decryptedKey); foreach (XmlElement el in doc.SelectNodes ("//o:Security/c:DerivedKeyToken", nsmgr)) { n = el.SelectSingleNode ("c:Offset", nsmgr); int offset = (n == null) ? 0 : int.Parse (n.InnerText, CultureInfo.InvariantCulture); n = el.SelectSingleNode ("c:Length", nsmgr); int length = (n == null) ? 32 : int.Parse (n.InnerText, CultureInfo.InvariantCulture); n = el.SelectSingleNode ("c:Label", nsmgr); byte [] label = (n == null) ? decryptedKey : Convert.FromBase64String (n.InnerText); n = el.SelectSingleNode ("c:Nonce", nsmgr); byte [] nonce = (n == null) ? new byte [0] : Convert.FromBase64String (n.InnerText); byte [] derkey = skey.GenerateDerivedKey ( //SecurityAlgorithms.Psha1KeyDerivation, "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1", // FIXME: maybe due to the label, this key resolution somehow does not seem to work. label, nonce, length * 8, offset); keys [el.GetAttribute ("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey; } #endif // decrypt the signature with the decrypted key #if true n = doc.SelectSingleNode ("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr); Assert.IsNotNull (n, "premise: encdata does not exist"); raw = n.InnerText; rawbytes = Convert.FromBase64String (raw); Rijndael aes = RijndaelManaged.Create (); // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)]; aes.Key = decryptedKey; aes.Mode = CipherMode.CBC; aes.Padding = mode; MemoryStream ms = new MemoryStream (); CryptoStream cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write); cs.Write (rawbytes, 0, rawbytes.Length); cs.Close (); byte [] decryptedSignature = ms.ToArray (); #else Rijndael aes = RijndaelManaged.Create (); // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)]; aes.Key = decryptedKey; aes.Mode = CipherMode.CBC; aes.Padding = mode; EncryptedData ed = new EncryptedData (); n = doc.SelectSingleNode ("//o:Security/e:EncryptedData", nsmgr); Assert.IsNotNull (n, "premise: encdata does not exist"); ed.LoadXml (n as XmlElement); byte [] decryptedSignature = encXml.DecryptData (ed, aes); #endif //Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature)); //Console.Error.WriteLine ("============= Decrypted Signature End ==========="); // decrypt the body with the decrypted key #if true n = doc.SelectSingleNode ("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr); Assert.IsNotNull (n, "premise: encdata does not exist"); raw = n.InnerText; rawbytes = Convert.FromBase64String (raw); // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)]; aes.Key = decryptedKey; ms = new MemoryStream (); cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write); cs.Write (rawbytes, 0, rawbytes.Length); cs.Close (); byte [] decryptedBody = ms.ToArray (); #else // decrypt the body with the decrypted key EncryptedData ed2 = new EncryptedData (); XmlElement el = doc.SelectSingleNode ("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement; ed2.LoadXml (el); // aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)]; aes.Key = decryptedKey; byte [] decryptedBody = encXml.DecryptData (ed2, aes); #endif //foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b); Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedBody)); Console.Error.WriteLine ("============= Decrypted Body End ==========="); // FIXME: find out what first 16 bytes mean. for (int mmm = 0; mmm < 16; mmm++) decryptedBody [mmm] = 0x20; doc.LoadXml (Encoding.UTF8.GetString (decryptedBody)); Assert.AreEqual ("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1"); Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2"); return doc.DocumentElement; }
/// <summary> /// Decrypts the assertion using the key given as the method parameter. The resulting assertion /// is available through the <code>Assertion</code> property. /// </summary> /// <exception cref="Saml20FormatException">Thrown if it not possible to decrypt the assertion.</exception> public void Decrypt() { if (TransportKey == null) { throw new InvalidOperationException("The \"TransportKey\" property must contain the asymmetric key to decrypt the assertion."); } if (_encryptedAssertion == null) { throw new InvalidOperationException("Unable to find the <EncryptedAssertion> element. Use a constructor or the LoadXml - method to set it."); } var encryptedDataElement = GetElement(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc, _encryptedAssertion.DocumentElement); var encryptedData = new EncryptedData(); encryptedData.LoadXml(encryptedDataElement); SymmetricAlgorithm sessionKey; if (encryptedData.EncryptionMethod != null) { _sessionKeyAlgorithm = encryptedData.EncryptionMethod.KeyAlgorithm; sessionKey = ExtractSessionKey(_encryptedAssertion, _sessionKeyAlgorithm); } else { sessionKey = ExtractSessionKey(_encryptedAssertion); } /* * NOTE: * The EncryptedXml class can't handle an <EncryptedData> element without an underlying <EncryptionMethod> element, * despite the standard dictating that this is ok. * If this becomes a problem with other IDPs, consider adding a default EncryptionMethod instance manually before decrypting. */ var encryptedXml = new EncryptedXml(); var plaintext = encryptedXml.DecryptData(encryptedData, sessionKey); Assertion = new XmlDocument { PreserveWhitespace = true }; try { Assertion.Load(new StringReader(Encoding.UTF8.GetString(plaintext))); } catch (XmlException e) { Assertion = null; throw new Saml20FormatException("Unable to parse the decrypted assertion.", e); } }
public void RoundtripSample1 () { StringWriter sw = new StringWriter (); // Encryption { XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; doc.LoadXml ("<root> <child>sample</child> </root>"); XmlElement body = doc.DocumentElement; RijndaelManaged aes = new RijndaelManaged (); 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 { 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.LoadXml (sw.ToString ()); EncryptedXml encxml = new EncryptedXml (doc); EncryptedData edata = new EncryptedData (); edata.LoadXml (doc.DocumentElement); encxml.ReplaceData (doc.DocumentElement, encxml.DecryptData (edata, aes)); } }
private bool ProcessEncryptedDataItem (XmlElement encryptedDataElement) { // first see whether we want to ignore this one if (ExceptUris.Count > 0) { for (int index = 0; index < ExceptUris.Count; index++) { if (IsTargetElement(encryptedDataElement, (string) ExceptUris[index])) return false; } } EncryptedData ed = new EncryptedData(); ed.LoadXml(encryptedDataElement); SymmetricAlgorithm symAlg = this.EncryptedXml.GetDecryptionKey(ed, null); if (symAlg == null) throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingDecryptionKey")); byte[] decrypted = EncryptedXml.DecryptData(ed, symAlg); ReplaceEncryptedData(encryptedDataElement, decrypted); return true; }
private bool ProcessEncryptedDataItem(XmlElement encryptedDataElement) { if (this.ExceptUris.Count > 0) { for (int i = 0; i < this.ExceptUris.Count; i++) { if (this.IsTargetElement(encryptedDataElement, (string) this.ExceptUris[i])) { return false; } } } EncryptedData encryptedData = new EncryptedData(); encryptedData.LoadXml(encryptedDataElement); SymmetricAlgorithm decryptionKey = this.EncryptedXml.GetDecryptionKey(encryptedData, null); if (decryptionKey == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingDecryptionKey")); } byte[] decrypted = this.EncryptedXml.DecryptData(encryptedData, decryptionKey); this.ReplaceEncryptedData(encryptedDataElement, decrypted); return true; }
// Methods private static void Decrypt(XmlDocument doc, SymmetricAlgorithm alg) { XmlElement element = doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; EncryptedData encryptedData = new EncryptedData(); encryptedData.LoadXml(element); EncryptedXml xml = new EncryptedXml(); byte[] decryptedData = xml.DecryptData(encryptedData, alg); xml.ReplaceData(element, decryptedData); }