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));
        }
Beispiel #2
0
        /// <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;
        }
        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);
        }
        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);
        }
Beispiel #6
0
		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));
			}
		}
        // Override EncryptedXml.GetDecryptionKey to avoid calling into CryptoConfig.CreateFromName
        // When detect AES, we need to return AesCryptoServiceProvider (FIPS certified) instead of AesManaged (FIPS obsolated)
        public override SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri) {
            
            // If AES is used then assume FIPS is required
            bool fipsRequired = IsAesDetected(encryptedData, symmetricAlgorithmUri);

            if (fipsRequired) {
                // Obtain the EncryptedKey
                EncryptedKey ek = null;

                foreach (var ki in encryptedData.KeyInfo) {
                    KeyInfoEncryptedKey kiEncKey = ki as KeyInfoEncryptedKey;
                    if (kiEncKey != null) {
                        ek = kiEncKey.EncryptedKey;
                        break;
                    }
                }

                // Got an EncryptedKey, decrypt it to get the AES key
                if (ek != null) {
                    byte[] key = DecryptEncryptedKey(ek);

                    // Construct FIPS-certified AES provider
                    if (key != null) {
                        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                        aes.Key = key;
                        
                        return aes;
                    }
                }
            }

            // Fallback to the base implementation
            return base.GetDecryptionKey(encryptedData, symmetricAlgorithmUri);
        }
        public override SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri)
        {
            SymmetricAlgorithm ret = null;
            try
            {
                //first we try to decrypt with the default implementation
                //which looks for ds:KeyName XML tags
                ret = base.GetDecryptionKey(encryptedData, symmetricAlgorithmUri);
            }
            catch (CryptographicException)
            {
                // now let's try it our way:
                ret = Saml2Utils.GetAlgorithm(encryptedData.EncryptionMethod.KeyAlgorithm);
                ret.IV = GetDecryptionIV(encryptedData, encryptedData.EncryptionMethod.KeyAlgorithm);
                X509Certificate2 decryptionKey =
                        FedletCertificateFactory.GetCertificateByFriendlyName(serviceProvider.EncryptionCertificateAlias);
                if (decryptionKey == null || !decryptionKey.HasPrivateKey)
                {
                    throw new CryptographicException(Resources.DecryptionKeyNotFound);
                }
                EncryptedKey encKey = null;
                foreach (KeyInfoClause clause in encryptedData.KeyInfo) {
			       if (clause is KeyInfoEncryptedKey) {
					    encKey = ((KeyInfoEncryptedKey) clause).EncryptedKey;
				       break;
				    }
			}
                ret.Key = DecryptKey(encKey.CipherData.CipherValue, (RSA)decryptionKey.PrivateKey, false);
            }
            return ret;
        }
        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 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.
        }
        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;

        }
        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;
        }
        /// <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 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;
 }
Beispiel #16
0
        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);
        }
Beispiel #17
0
        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);
        }
        private static bool IsAesDetected(EncryptedData encryptedData, string symmetricAlgorithmUri) {
            if (encryptedData != null &&
                encryptedData.KeyInfo != null &&
                (symmetricAlgorithmUri != null || encryptedData.EncryptionMethod != null)) {

                if (symmetricAlgorithmUri == null) {
                    symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
                }

                // Check if the Uri matches AES256
                return string.Equals(symmetricAlgorithmUri, EncryptedXml.XmlEncAES256Url, StringComparison.InvariantCultureIgnoreCase);
            }

            return false;
        }
Beispiel #19
0
		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 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 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 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 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;
        }
        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);
        }
Beispiel #25
0
		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));
			}
		}
Beispiel #26
0
        //
        // public static methods
        //

        // replaces the inputElement with the provided EncryptedData
        public static void ReplaceElement (XmlElement inputElement, EncryptedData encryptedData, bool content) {
            if (inputElement == null)
                throw new ArgumentNullException("inputElement");
            if (encryptedData == null)
                throw new ArgumentNullException("encryptedData");

            // First, get the XML representation of the EncryptedData object
            XmlElement elemED = encryptedData.GetXml(inputElement.OwnerDocument);
            switch (content) {
            case true:
                // remove all children of the input element
                Utils.RemoveAllChildren(inputElement);
                // then append the encrypted data as a child of the input element
                inputElement.AppendChild(elemED);
                break;
            case false:
                XmlNode parentNode = inputElement.ParentNode;
                // remove the input element from the containing document
                parentNode.ReplaceChild(elemED, inputElement);
                break;
            }
        }
Beispiel #27
0
        // decrypts the supplied EncryptedData
        public byte[] DecryptData (EncryptedData encryptedData, SymmetricAlgorithm symmetricAlgorithm) {
            if (encryptedData == null)
                throw new ArgumentNullException("encryptedData");
            if (symmetricAlgorithm == null)
                throw new ArgumentNullException("symmetricAlgorithm");

            // get the cipher value and decrypt
            byte[] cipherValue = GetCipherValue(encryptedData.CipherData);

            // save the original symmetric algorithm
            CipherMode origMode = symmetricAlgorithm.Mode;
            PaddingMode origPadding = symmetricAlgorithm.Padding;
            byte[] origIV = symmetricAlgorithm.IV;

            // read the IV from cipherValue
            byte[] decryptionIV = null;
            if (m_mode != CipherMode.ECB)
                decryptionIV = GetDecryptionIV(encryptedData, null);

            byte[] output = null;
            try {
                int lengthIV = 0;
                if (decryptionIV != null) {
                    symmetricAlgorithm.IV = decryptionIV;
                    lengthIV = decryptionIV.Length;
                }
                symmetricAlgorithm.Mode = m_mode;
                symmetricAlgorithm.Padding = m_padding;

                ICryptoTransform dec = symmetricAlgorithm.CreateDecryptor();
                output = dec.TransformFinalBlock(cipherValue, lengthIV, cipherValue.Length - lengthIV);
            } finally {
                // now restore the original symmetric algorithm
                symmetricAlgorithm.Mode = origMode;
                symmetricAlgorithm.Padding = origPadding;
                symmetricAlgorithm.IV = origIV;
            }

            return output;
        }
Beispiel #28
0
 // 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);
         }
     }
 }
Beispiel #29
0
        // 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 == null)
                throw new ArgumentNullException("inputElement");
            if (keyName == null)
                throw new ArgumentNullException("keyName");

            Object encryptionKey = null;
            if (m_keyNameMapping != null)
                encryptionKey = m_keyNameMapping[keyName];

            if (encryptionKey == null)
                throw new CryptographicException(SecurityResources.GetResourceString("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;
            } else if (symKey is Rijndael || symKey is Aes) {
                // 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(SecurityResources.GetResourceString("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.
            RijndaelManaged rijn = new RijndaelManaged();
            ek.CipherData.CipherValue = (symKey == null ? EncryptedXml.EncryptKey(rijn.Key, rsa, false) : EncryptedXml.EncryptKey(rijn.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, rijn, false);

            return ed;
        }
Beispiel #30
0
        // Encrypts the given element with the certificate specified. The certificate is added as
        // an X509Data KeyInfo to an EncryptedKey (AES session key) generated randomly.
        public EncryptedData Encrypt (XmlElement inputElement, X509Certificate2 certificate) {
            if (inputElement == null)
                throw new ArgumentNullException("inputElement");
            if (certificate == null)
                throw new ArgumentNullException("certificate");

            if (X509Utils.OidToAlgId(certificate.PublicKey.Oid.Value) != CAPI.CALG_RSA_KEYX)
                throw new NotSupportedException(SecurityResources.GetResourceString("NotSupported_KeyAlgorithm"));

            // 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 certificate in the EncryptedKey KeyInfo.
            EncryptedKey ek = new EncryptedKey();
            ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
            ek.KeyInfo.AddClause(new KeyInfoX509Data(certificate));

            // Create a random AES session key and encrypt it with the public key associated with the certificate.
            RijndaelManaged rijn = new RijndaelManaged();
            ek.CipherData.CipherValue = EncryptedXml.EncryptKey(rijn.Key, certificate.PublicKey.Key as RSA, false);

            // 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, rijn, false);

            return ed;
        }
Beispiel #31
0
        // default behaviour is to look for keys defined by an EncryptedKey clause
        // either directly or through a KeyInfoRetrievalMethod, and key names in the key mapping
        public virtual SymmetricAlgorithm GetDecryptionKey (EncryptedData encryptedData, string symmetricAlgorithmUri) {
            if (encryptedData == null)
                throw new ArgumentNullException("encryptedData");

            if (encryptedData.KeyInfo == null)
                return null;
            IEnumerator keyInfoEnum = encryptedData.KeyInfo.GetEnumerator();
            KeyInfoRetrievalMethod kiRetrievalMethod;
            KeyInfoName kiName;
            KeyInfoEncryptedKey kiEncKey;
            EncryptedKey ek = null;

            while (keyInfoEnum.MoveNext()) {
                kiName = keyInfoEnum.Current as KeyInfoName;
                if (kiName != null) {
                    // Get the decryption key from the key mapping
                    string keyName = kiName.Value;
                    if ((SymmetricAlgorithm) m_keyNameMapping[keyName] != null) 
                        return (SymmetricAlgorithm) m_keyNameMapping[keyName];
                    // try to get it from a CarriedKeyName
                    XmlNamespaceManager nsm = new XmlNamespaceManager(m_document.NameTable);
                    nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
                    XmlNodeList encryptedKeyList = m_document.SelectNodes("//enc:EncryptedKey", nsm);
                    if (encryptedKeyList != null) {
                        foreach (XmlNode encryptedKeyNode in encryptedKeyList) {
                            XmlElement encryptedKeyElement = encryptedKeyNode as XmlElement;
                            EncryptedKey ek1 = new EncryptedKey();
                            ek1.LoadXml(encryptedKeyElement);
                            if (ek1.CarriedKeyName == keyName && ek1.Recipient == this.Recipient) {
                                ek = ek1;
                                break;
                            }
                        }
                    }
                    break;
                }
                kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
                if (kiRetrievalMethod != null) { 
                    string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri);
                    ek = new EncryptedKey();
                    ek.LoadXml(GetIdElement(m_document, idref));
                    break;
                }
                kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
                if (kiEncKey != null) {
                    ek = kiEncKey.EncryptedKey;
                    break;
                }
            }

            // if we have an EncryptedKey, decrypt to get the symmetric key
            if (ek != null) {
                // now process the EncryptedKey, loop recursively 
                // If the Uri is not provided by the application, try to get it from the EncryptionMethod
                if (symmetricAlgorithmUri == null) {
                    if (encryptedData.EncryptionMethod == null)
                        throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingAlgorithm"));
                    symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
                }
                byte[] key = DecryptEncryptedKey(ek);
                if (key == null)
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingDecryptionKey"));

                SymmetricAlgorithm symAlg = (SymmetricAlgorithm) CryptoConfig.CreateFromName(symmetricAlgorithmUri);
                symAlg.Key = key;
                return symAlg;
            }
            return null;
        }
Beispiel #32
0
        /// <summary>
        /// Retrieves a certificate from the Personal Certificate Store in Windows.
        /// </summary>
        /// <param name="sujetoCertificado"></param>
        /// <returns></returns>
        static void Encriptar(ref XmlDocument document, string elementoParaEncriptar, X509Certificate2 certificadopublico, ref XmlElement securityNode)
        {
            RSACryptoServiceProvider rsaAlgorithm = (RSACryptoServiceProvider)certificadopublico.PublicKey.Key; //llave publica usada para encriptar.


            //Ahora creamos un BinarySecurityToken que será el certificado x509 de la clave pública
            //se usa para que el receptor sepa qué certificado se usó para encriptar.
            XmlElement binarySecurityTokenNode = document.CreateElement("wsse", "BinarySecurityToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

            //El atributo EncodingType dice cómo el Token está codificado, en este caso, Base64Binary.
            binarySecurityTokenNode.SetAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
            //El atributo ValueType indica qué es el BinarySecurityToken, en este caso un Certificado X509v3.
            binarySecurityTokenNode.SetAttribute("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");

            binarySecurityTokenNode.SetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", XmlElementsIds.PublicKeyBinarySecurityTokenUri);
            XmlAttribute attribute = binarySecurityTokenNode.GetAttributeNode("Id");

            attribute.Prefix = "wsu";
            binarySecurityTokenNode.InnerText = Convert.ToBase64String(certificadopublico.GetRawCertData());


            //Creamos una llave simétrica la cuál servirá para codificar la información. //AES-128-CBC
            AesManaged algoritmosimetrico = new AesManaged()
            {
                Padding = PaddingMode.ISO10126,
                KeySize = 128,
                Mode    = CipherMode.CBC,
            };

            System.Security.Cryptography.Xml.EncryptedKey encryptedKey = new System.Security.Cryptography.Xml.EncryptedKey();
            encryptedKey.EncryptionMethod = new System.Security.Cryptography.Xml.EncryptionMethod(EncryptedXml.XmlEncRSAOAEPUrl);
            encryptedKey.AddReference(new DataReference("#ED-31"));
            SecurityTokenReference securityTokenReference = new SecurityTokenReference();

            securityTokenReference.Reference = XmlElementsIds.PublicKeyBinarySecurityTokenUri;
            securityTokenReference.ValueType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
            KeyInfo ekkeyInfo = new KeyInfo();

            ekkeyInfo.AddClause(new KeyInfoNode(securityTokenReference.GetXml()));
            encryptedKey.KeyInfo    = ekkeyInfo;
            encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(algoritmosimetrico.Key, rsaAlgorithm, true));



            securityNode.PrependChild(document.ImportNode(encryptedKey.GetXml(), true));
            securityNode.PrependChild(binarySecurityTokenNode);



            //Crear un XmlElement a través del nombre del Tag que se encuentra en el documento Xml especificado.
            XmlElement elementoParaEncriptarXML = document.GetElementsByTagName(elementoParaEncriptar)[0] as XmlElement;



            //Creamos una instancia de la clase EncryptedXml y usarla para encriptar
            //el XmlElement: elementoParaEncriptarXML; usando la llave simétrica que acabamos de
            //crear.
            EncryptedXml xmlEncriptado = new EncryptedXml();

            //Encriptamos el Body (elementoParaEncriptarXML) usando el algoritmo simétrico AES-128-CBC y lo dejamos ahí.
            byte[] elementoEncriptado = xmlEncriptado.EncryptData(elementoParaEncriptarXML, algoritmosimetrico, false);


            //Ahora creamos una instancia de la clase EncryptedData que representa
            //un elemento <EncryptedData> en el documento XML.
            System.Security.Cryptography.Xml.EncryptedData encryptedData = new System.Security.Cryptography.Xml.EncryptedData()
            {
                Type = EncryptedXml.XmlEncElementContentUrl,
                Id   = "ED-31",

                //Le asignamos otra propiedad a este elemento <EncryptedData> que es un EncryptionMethod
                //para que el receptor sepa que algoritmo usar para descifrar
                EncryptionMethod = new System.Security.Cryptography.Xml.EncryptionMethod(EncryptedXml.XmlEncAES128Url) //Aes-128-cbc o Rjindael.
            };
            encryptedData.CipherData = new CipherData(elementoEncriptado);

            /* Para descencriptar: Funciona, es para testear si puedo desencriptar los datos.
             * var lmao= xmlEncriptado.DecryptData(encryptedData, algoritmosimetrico);
             * var decrypted = Encoding.UTF8.GetString(lmao);
             */

            //Reemplazamos el elemento quotationCarGenericRq sin encriptar del documento XML con el elemento <EncryptedData> (que contiene el Body y sus contenidos encriptados) básicamente.
            //totalmente lleno.
            EncryptedXml.ReplaceElement(elementoParaEncriptarXML, encryptedData, false);
        }
 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;
 }
        internal static void Encrypt(this XmlElement elementToEncrypt, EncryptingCredentials encryptingCredentials)
        {
            if (elementToEncrypt == null)
            {
                throw new ArgumentNullException(nameof(elementToEncrypt));
            }
            if (encryptingCredentials == null)
            {
                throw new ArgumentNullException(nameof(encryptingCredentials));
            }

            string enc;
            int    keySize;

            switch (encryptingCredentials.Enc)
            {
            case SecurityAlgorithms.Aes128CbcHmacSha256:
                enc     = EncryptedXml.XmlEncAES128Url;
                keySize = 128;
                break;

            case SecurityAlgorithms.Aes192CbcHmacSha384:
                enc     = EncryptedXml.XmlEncAES192Url;
                keySize = 192;
                break;

            case SecurityAlgorithms.Aes256CbcHmacSha512:
                enc     = EncryptedXml.XmlEncAES256Url;
                keySize = 256;
                break;

            default:
                throw new CryptographicException(
                          $"Unsupported cryptographic algorithm {encryptingCredentials.Enc}");
            }

            var encryptedData = new EncryptedData
            {
                Type             = EncryptedXml.XmlEncElementUrl,
                EncryptionMethod = new EncryptionMethod(enc)
            };

            string alg;

            switch (encryptingCredentials.Alg)
            {
            case SecurityAlgorithms.RsaOAEP:
                alg = EncryptedXml.XmlEncRSAOAEPUrl;
                break;

            case SecurityAlgorithms.RsaPKCS1:
                alg = EncryptedXml.XmlEncRSA15Url;
                break;

            default:
                throw new CryptographicException(
                          $"Unsupported cryptographic algorithm {encryptingCredentials.Alg}");
            }
            var encryptedKey = new EncryptedKey
            {
                EncryptionMethod = new EncryptionMethod(alg),
            };

            var encryptedXml = new EncryptedXml();

            byte[] encryptedElement;
            using (var symmetricAlgorithm = new RijndaelManaged())
            {
                X509SecurityKey x509SecurityKey = encryptingCredentials.Key as X509SecurityKey;
                if (x509SecurityKey == null)
                {
                    throw new CryptographicException(
                              "The encrypting credentials have an unknown key of type {encryptingCredentials.Key.GetType()}");
                }

                symmetricAlgorithm.KeySize = keySize;
                encryptedKey.CipherData    = new CipherData(EncryptedXml.EncryptKey(symmetricAlgorithm.Key,
                                                                                    (RSA)x509SecurityKey.PublicKey, alg == EncryptedXml.XmlEncRSAOAEPUrl));
                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);
        }