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 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;
 }
 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();
        }
Ejemplo n.º 9
0
        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;
        }
Ejemplo n.º 10
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));
			}
		}
Ejemplo n.º 11
0
		public void EncryptData_XmlElementNull ()
		{
			EncryptedXml ex = new EncryptedXml ();
			ex.EncryptData (null, Rijndael.Create (), true);
		}
Ejemplo n.º 12
0
		public void EncryptData_SymmetricAlgorithmNull ()
		{
			EncryptedXml ex = new EncryptedXml ();
			ex.EncryptData (new byte[16], null);
		}
Ejemplo n.º 13
0
		public void EncryptData_DataNull ()
		{
			EncryptedXml ex = new EncryptedXml ();
			ex.EncryptData (null, Rijndael.Create ());
		}
Ejemplo n.º 14
0
        public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string KeyName)
        {
            // Check the arguments.
            if (Doc == null)
                throw new ArgumentNullException("Doc");
            if (ElementToEncrypt == null)
                throw new ArgumentNullException("ElementToEncrypt");
            if (EncryptionElementID == null)
                throw new ArgumentNullException("EncryptionElementID");
            if (Alg == null)
                throw new ArgumentNullException("Alg");
            if (KeyName == null)
                throw new ArgumentNullException("KeyName");

            ////////////////////////////////////////////////
            // Find the specified element in the XmlDocument
            // object and create a new XmlElemnt object.
            ////////////////////////////////////////////////
            XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;

            // Throw an XmlException if the element was not found.
            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");

            }
            RijndaelManaged sessionKey = null;

            try
            {
                //////////////////////////////////////////////////
                // Create a new instance of the EncryptedXml class
                // and use it to encrypt the XmlElement with the
                // a new random symmetric key.
                //////////////////////////////////////////////////

                // Create a 256 bit Rijndael key.
                sessionKey = new RijndaelManaged();
                sessionKey.KeySize = 256;

                EncryptedXml eXml = new EncryptedXml();

                byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false);
                ////////////////////////////////////////////////
                // Construct an EncryptedData object and populate
                // it with the desired encryption information.
                ////////////////////////////////////////////////

                EncryptedData edElement = new EncryptedData();
                edElement.Type = EncryptedXml.XmlEncElementUrl;
                edElement.Id = EncryptionElementID;
                // Create an EncryptionMethod element so that the
                // receiver knows which algorithm to use for decryption.

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

                ek.CipherData = new CipherData(encryptedKey);

                ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);

                // Create a new DataReference element
                // for the KeyInfo element.  This optional
                // element specifies which EncryptedData
                // uses this key.  An XML document can have
                // multiple EncryptedData elements that use
                // different keys.
                DataReference dRef = new DataReference();

                // Specify the EncryptedData URI.
                dRef.Uri = "#" + EncryptionElementID;

                // Add the DataReference to the EncryptedKey.
                ek.AddReference(dRef);
                // Add the encrypted key to the
                // EncryptedData object.

                edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));
                // Set the KeyInfo element to specify the
                // name of the RSA key.

                // Create a new KeyInfo element.
                edElement.KeyInfo = new KeyInfo();

                // Create a new KeyInfoName element.
                KeyInfoName kin = new KeyInfoName();

                // Specify a name for the key.
                kin.Value = KeyName;

                // Add the KeyInfoName element to the
                // EncryptedKey object.
                ek.KeyInfo.AddClause(kin);
                // Add the encrypted element data to the
                // EncryptedData object.
                edElement.CipherData.CipherValue = encryptedElement;
                ////////////////////////////////////////////////////
                // Replace the element from the original XmlDocument
                // object with the EncryptedData element.
                ////////////////////////////////////////////////////
                EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
            }
            catch (Exception e)
            {
                // re-throw the exception.
                throw e;
            }
            finally
            {
                if (sessionKey != null)
                {
                    sessionKey.Clear();
                }

            }

        }
Ejemplo n.º 15
0
Archivo: Form1.cs Proyecto: dxk/Encrypt
 //加密
 private void btnJiaMi_Click(object sender, EventArgs e)
 {
     if (label1.Text == "")
     {
         return;
     }
     try
     {
         //生产对称密钥.该密钥用来对XML加密
         RijndaelManaged key = new RijndaelManaged();
         keyIv = key.IV;
         keyKey = key.Key;
         //加载XML对象,定制加密位置
         XmlDocument xmlDoc = new XmlDocument();
         xmlDoc.PreserveWhitespace = true;
         xmlDoc.Load(this.label1.Text);
         XmlElement elementToEncrypt = xmlDoc.GetElementsByTagName("creditcard")[0] as XmlElement;
         //生产EncrypteData类
         EncryptedData edElement = new EncryptedData();
         edElement.Type = EncryptedXml.XmlEncElementUrl;//填充Url标识符
         string encryptionMethod = null;
         if (key is TripleDES)
         {
             encryptionMethod = EncryptedXml.XmlEncTripleDESUrl;
         }
         else if (key is DES)
         {
             encryptionMethod = EncryptedXml.XmlEncDESUrl;
         }
         if (key is Rijndael)
         {
             switch (key.KeySize)
             {
                 case 128:
                     encryptionMethod = EncryptedXml.XmlEncAES128Url;
                     break;
                 case 192:
                     encryptionMethod = EncryptedXml.XmlEncAES192Url;
                     break;
                 case 256:
                     encryptionMethod = EncryptedXml.XmlEncAES256Url;
                     break;
             }
         }
         else
         {
             throw new CryptographicException("没有为XML加密的指定算法!");
         }
         edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);//生成具有加密算法的Url标识符
         //用EncryptedXml加密xml
         EncryptedXml eXml = new EncryptedXml();
         byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, key, false);
         //把加密的元素添加到EncryptedData中
         edElement.CipherData.CipherValue = encryptedElement;
         //最后将xml中原始数据和EncrytedXml替换
         EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
         xmlDoc.Save(this.label1.Text);
         succes();
     }
     catch (Exception ex)
     {
         fail();
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Encrypts the Assertion in the assertion property and creates an <code>EncryptedAssertion</code> element
        /// that can be retrieved using the <code>GetXml</code> method.
        /// </summary>
        public void Encrypt()
        {
            if (TransportKey == null)
            {
                throw new InvalidOperationException("The \"TransportKey\" property is required to encrypt the assertion.");
            }
            
            if (Assertion == null)
            {
                throw new InvalidOperationException("The \"Assertion\" property is required for this operation.");
            }

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

            // Encrypt the assertion and add it to the encryptedData instance.
            var encryptedXml = new EncryptedXml();
            var encryptedElement = encryptedXml.EncryptData(Assertion.DocumentElement, SessionKey, false);
            encryptedData.CipherData.CipherValue = encryptedElement;

            // Add an encrypted version of the key used.
            encryptedData.KeyInfo = new KeyInfo();

            var encryptedKey = new EncryptedKey
                                   {
                                       EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url),
                                       CipherData = new CipherData(EncryptedXml.EncryptKey(SessionKey.Key, TransportKey, false))
                                   };
            encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));

            // Create an empty EncryptedAssertion to hook into.
            var encryptedAssertion = new EncryptedAssertion { EncryptedData = new Schema.XEnc.EncryptedData() };

            var result = new XmlDocument();
            result.LoadXml(Serialization.SerializeToXmlString(encryptedAssertion));

            var encryptedDataElement = GetElement(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc, result.DocumentElement);
            EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false);

            _encryptedAssertion = result;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Encrypts the NameID attribute of the AttributeQuery request.
        /// </summary>
        /// <param name="certFriendlyName">
        /// Friendly Name of the X509Certificate to be retrieved
        /// from the LocalMachine keystore and used to encrypt generated symmetric key.
        /// Be sure to have appropriate permissions set on the keystore.
        /// </param>
        /// <param name="xmlDoc">
        /// XML document to be encrypted.
        /// </param>
        /// <param name="symmetricAlgorithmUri">
        /// Symmetric algorithm uri used for encryption.
        /// </param>
        public static void EncryptAttributeQueryNameID(string certFriendlyName, string symmetricAlgorithmUri, XmlDocument xmlDoc)
        {
            if (string.IsNullOrWhiteSpace(certFriendlyName))
            {
                throw new Saml2Exception(Resources.EncryptedXmlInvalidCertFriendlyName);
            }

            if (string.IsNullOrWhiteSpace(symmetricAlgorithmUri))
            {
                throw new Saml2Exception(Resources.EncryptedXmlInvalidEncrAlgorithm);
            }

            if (xmlDoc == null)
            {
                throw new Saml2Exception(Resources.SignedXmlInvalidXml);
            }

            X509Certificate2 cert = FedletCertificateFactory.GetCertificateByFriendlyName(certFriendlyName);
            if (cert == null)
            {
                throw new Saml2Exception(Resources.EncryptedXmlCertNotFound);
            }

            XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
            nsMgr.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            nsMgr.AddNamespace("saml", Saml2Constants.NamespaceSamlAssertion);
            nsMgr.AddNamespace("samlp", Saml2Constants.NamespaceSamlProtocol);

            string xpath = "/samlp:AttributeQuery/saml:Subject/saml:NameID";
            XmlNode root = xmlDoc.DocumentElement;
            XmlNode node = root.SelectSingleNode(xpath, nsMgr);

            XmlNode encryptedID = xmlDoc.CreateNode(XmlNodeType.Element, "EncryptedID", Saml2Constants.NamespaceSamlAssertion);
            node.ParentNode.PrependChild(encryptedID);

            XmlElement elementToEncrypt = (XmlElement)encryptedID.AppendChild(node.Clone());
            if (elementToEncrypt == null)
            {
                throw new Saml2Exception(Resources.EncryptedXmlInvalidXml);
            }
            encryptedID.ParentNode.RemoveChild(node);

            SymmetricAlgorithm alg = Saml2Utils.GetAlgorithm(symmetricAlgorithmUri);

            if (alg == null)
            {
                throw new Saml2Exception(Resources.EncryptedXmlInvalidEncrAlgorithm);
            }

            alg.GenerateKey();

            string encryptionElementID = Saml2Utils.GenerateId();
            string encryptionKeyElementID = Saml2Utils.GenerateId();
            EncryptedData encryptedData = new EncryptedData();
            encryptedData.Type = EncryptedXml.XmlEncElementUrl;
            encryptedData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES128Url);
            encryptedData.Id = encryptionElementID;

            EncryptedXml encryptedXml = new EncryptedXml();
            byte[] encryptedElement = encryptedXml.EncryptData(elementToEncrypt, alg, false);
            encryptedData.CipherData.CipherValue = encryptedElement;
            encryptedData.KeyInfo = new KeyInfo();

            EncryptedKey encryptedKey = new EncryptedKey();
            encryptedKey.Id = encryptionKeyElementID;
            RSA publicKeyRSA = cert.PublicKey.Key as RSA;
            encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
            encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(alg.Key, publicKeyRSA, false));

            encryptedData.KeyInfo.AddClause(new KeyInfoRetrievalMethod("#" + encryptionKeyElementID, "http://www.w3.org/2001/04/xmlenc#EncryptedKey"));

            KeyInfoName kin = new KeyInfoName();
            kin.Value = cert.SubjectName.Name;
            encryptedKey.KeyInfo.AddClause(kin);

            EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false);

            XmlNode importKeyNode = xmlDoc.ImportNode(encryptedKey.GetXml(), true);
            encryptedID.AppendChild(importKeyNode);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Doc"></param>
        /// <param name="ElementName">Ruta completa del elemento a encriptar
        /// Ejemplos:
        /// <example>
        /// Encripta el precio los libros cuyo precio es mayor a 35
        /// /bookstore/book[price>35]/price 
        /// 
        /// Busca el grupos "ValidationExceptionMessage" y dentro de este la clave con nombre "MaxLenghtField" 
        ///         "/ConfigurationFile/Groups/Group[@name='ValidationExceptionMessage']/Keys/Key[@name='MaxLenghtField']"
        ///         
        /// 
        /// "//EXAMPLE/CUSTOMER[substring(@type,1,2) ='DE']"
        /// "//EXAMPLE/CUSTOMER[contains(@type,'DECEA')]"
        /// </example>
        /// </param>
        /// <param name="Key"></param>
        public static string Encrypt(string xml, string elementPath, SymmetricAlgorithm symmetricAlgorithm)
        {

            // Check the arguments.  
            if (string.IsNullOrEmpty(xml))
                throw new ArgumentNullException("xml");
            if (string.IsNullOrEmpty(elementPath))
                throw new ArgumentNullException("elementPath");
            if (symmetricAlgorithm == null)
                throw new ArgumentNullException("SymmetricAlgorithm");


            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(xml);

            ///bookstore/book[price>35]/price 
            /// "/ConfigurationFile/Groups/Group[@name='ValidationExceptionMessage']/Keys/Key[@name='MaxLenghtField']"
            XmlElement elementToEncrypt = xmlDoc.SelectSingleNode(elementPath) as XmlElement;

            // Throw an XmlException if the element was not found.
            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");

            }


            //////////////////////////////////////////////////
            // Creo una instancia de EncryptedXml y la uso 
            // para encriptar XmlElement con lka clave simetrica
            //////////////////////////////////////////////////
            EncryptedXml eXml = new EncryptedXml();

            
            byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, symmetricAlgorithm, false);

            // Construct an EncryptedData object and populate
            // it with the desired encryption information.
            EncryptedData edElement = new EncryptedData();
            edElement.Type = EncryptedXml.XmlEncElementUrl;
            edElement.EncryptionMethod = GetEncrypTionMethod(symmetricAlgorithm);

            //// Add the encrypted element data to the EncryptedData object.
            edElement.CipherData.CipherValue = encryptedElement;

            // Create a new KeyInfo element.
            edElement.KeyInfo = new KeyInfo();


            //// Encrypt the session key and add it to an EncryptedKey element.
            //EncryptedKey ek = new EncryptedKey();


            //// Create a new KeyInfoName element.
            //KeyInfoName kin = new KeyInfoName();

            //// Specify a name for the key.
            //kin.Value = KeyName;

            //// Add the KeyInfoName element to the 
            //// EncryptedKey object.
            //ek.KeyInfo.AddClause(kin);

            // Add the encrypted key to the 
            // EncryptedData object.

            //edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));




            // Replace the element from the original XmlDocument   object with the EncryptedData element.
            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
            symmetricAlgorithm.Clear();
            xml = xmlDoc.InnerXml;
            xmlDoc = null;
            return xml;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Generates an encrypted assertion and writes it to disk. 
        /// </summary>
        public static void GenerateEncryptedAssertion()
        {
            var assertion = AssertionUtil.GetTestAssertion();

            // Create an EncryptedData instance to hold the results of the encryption.o
            var encryptedData = new EncryptedData
                                    {
                                        Type = EncryptedXml.XmlEncElementUrl,
                                        EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url)
                                    };

            // Create a symmetric key.
            var aes = new RijndaelManaged { KeySize = 256 };
            aes.GenerateKey();

            // Encrypt the assertion and add it to the encryptedData instance.
            var encryptedXml = new EncryptedXml();
            var encryptedElement = encryptedXml.EncryptData(assertion.DocumentElement, aes, false);
            encryptedData.CipherData.CipherValue = encryptedElement;

            // Add an encrypted version of the key used.
            encryptedData.KeyInfo = new KeyInfo();

            var encryptedKey = new EncryptedKey();

            // Use this certificate to encrypt the key.
            var cert = new X509Certificate2(@"Certificates\sts_dev_certificate.pfx", "test1234");
            var 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.
            var encryptedAssertion = new EncryptedAssertion
                                         {
                                             EncryptedData = new Schema.XEnc.EncryptedData(),
                                             EncryptedKey = new Schema.XEnc.EncryptedKey[1]
                                         };
            encryptedAssertion.EncryptedKey[0] = new Schema.XEnc.EncryptedKey();

            var result = Serialization.Serialize(encryptedAssertion);

            var encryptedDataElement = GetElement(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc, result);
            EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false);

            // At this point, result can be output to text
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Encrypt.
        /// </summary>
        /// <param name="Doc">XML document.</param>
        /// <param name="ElementToEncrypt">Element to encrypt.</param>
        /// <param name="Alg">Algoritm.</param>
        /// <param name="KeyName">Key name.</param>
        public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, RSA Alg, string KeyName)
        {
            // Check the arguments.
            if (Doc == null)
                throw new ArgumentNullException("Doc");
            if (ElementToEncrypt == null)
                throw new ArgumentNullException("ElementToEncrypt");
            if (Alg == null)
                throw new ArgumentNullException("Alg");

            ////////////////////////////////////////////////
            // Find the specified element in the XmlDocument
            // object and create a new XmlElemnt object.
            ////////////////////////////////////////////////

            XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;

            // Throw an XmlException if the element was not found.
            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");

            }

            //////////////////////////////////////////////////
            // Create a new instance of the EncryptedXml class
            // and use it to encrypt the XmlElement with the
            // a new random symmetric key.
            //////////////////////////////////////////////////

            // Create a 256 bit Rijndael key.
            RijndaelManaged sessionKey = new RijndaelManaged();
            sessionKey.KeySize = 256;

            EncryptedXml eXml = new EncryptedXml();

            byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, sessionKey, false);

            ////////////////////////////////////////////////
            // Construct an EncryptedData object and populate
            // it with the desired encryption information.
            ////////////////////////////////////////////////

            EncryptedData edElement = new EncryptedData();
            edElement.Type = EncryptedXml.XmlEncElementUrl;

            // Create an EncryptionMethod element so that the
            // receiver knows which algorithm to use for decryption.

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

            ek.CipherData = new CipherData(encryptedKey);

            ek.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);

            // Set the KeyInfo element to specify the
            // name of the RSA key.

            // Create a new KeyInfo element.
            edElement.KeyInfo = new KeyInfo();

            // Create a new KeyInfoName element.
            KeyInfoName kin = new KeyInfoName();

            // Specify a name for the key.
            kin.Value = KeyName;

            // Add the KeyInfoName element to the
            // EncryptedKey object.
            ek.KeyInfo.AddClause(kin);

            // Add the encrypted key to the
            // EncryptedData object.

            edElement.KeyInfo.AddClause(new KeyInfoEncryptedKey(ek));

            // Add the encrypted element data to the
            // EncryptedData object.
            edElement.CipherData.CipherValue = encryptedElement;

            ////////////////////////////////////////////////////
            // Replace the element from the original XmlDocument
            // object with the EncryptedData element.
            ////////////////////////////////////////////////////

            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
        }
        /// <summary>
        /// Encrypts the Assertion in the assertion property and creates an <code>EncryptedAssertion</code> element
        /// that can be retrieved using the <code>GetXml</code> method.
        /// </summary>
        public void Encrypt()
        {
            if (_transportKey == null)
                throw new InvalidOperationException("The \"TransportKey\" property is required to encrypt the assertion.");
            
            if (_assertion == null)
                throw new InvalidOperationException("The \"Assertion\" property is required for this operation.");

            EncryptedData encryptedData = new EncryptedData();
            encryptedData.Type = EncryptedXml.XmlEncElementUrl;

            encryptedData.EncryptionMethod = new EncryptionMethod(_sessionKeyAlgorithm);

            // Encrypt the assertion and add it to the encryptedData instance.
            EncryptedXml encryptedXml = new EncryptedXml();
            byte[] encryptedElement = encryptedXml.EncryptData(_assertion.DocumentElement, SessionKey, false);
            encryptedData.CipherData.CipherValue = encryptedElement;

            // Add an encrypted version of the key used.
            encryptedData.KeyInfo = new KeyInfo();

            EncryptedKey encryptedKey = new EncryptedKey();            
            encryptedKey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url);
            encryptedKey.CipherData = new CipherData(EncryptedXml.EncryptKey(SessionKey.Key, TransportKey, false));
            encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));

            // Create an empty EncryptedAssertion to hook into.
            EncryptedAssertion encryptedAssertion = new EncryptedAssertion();
            encryptedAssertion.encryptedData = new SfwEncryptedData();

            XmlDocument result = new XmlDocument();
            result.LoadXml(Serialization.SerializeToXmlString(encryptedAssertion));

            XmlElement encryptedDataElement = GetElement(SfwEncryptedData.ELEMENT_NAME, Saml20Constants.XENC, result.DocumentElement);
            EncryptedXml.ReplaceElement(encryptedDataElement, encryptedData, false);

            _encryptedAssertion = result;
        }        
Ejemplo n.º 22
0
		EncryptedData Encrypt (XmlElement target, SymmetricAlgorithm actualKey, string ekeyId, ReferenceList refList, SecurityKeyIdentifierClause encClause, EncryptedXml exml, XmlDocument doc)
		{
			SecurityAlgorithmSuite suite = security.Element.DefaultAlgorithmSuite;
			SecurityTokenSerializer serializer = security.TokenSerializer;

			byte [] encrypted = exml.EncryptData (target, actualKey, false);
			EncryptedData edata = new EncryptedData ();
			edata.Id = GenerateId (doc);
			edata.Type = EncryptedXml.XmlEncElementContentUrl;
			edata.EncryptionMethod = new EncryptionMethod (suite.DefaultEncryptionAlgorithm);
			// FIXME: here wsse:DigestMethod should be embedded 
			// inside EncryptionMethod. Since it is not possible 
			// with S.S.C.Xml.EncryptionMethod, we will have to
			// build our own XML encryption classes.

			edata.CipherData.CipherValue = encrypted;

			DataReference dr = new DataReference ();
			dr.Uri = "#" + edata.Id;
			refList.Add (dr);

			if (ShouldOutputEncryptedKey && !CounterParameters.RequireDerivedKeys)
				edata.KeyInfo = null;
			else {
				edata.KeyInfo = new KeyInfo ();
				edata.KeyInfo.AddClause (new SecurityTokenReferenceKeyInfo (encClause, serializer, doc));
			}

			return edata;
		}
Ejemplo n.º 23
0
        /// <summary>
        /// 加密数据.
        /// </summary>
        /// <param name="Doc"></param>
        /// <param name="ElementName"></param>
        /// <param name="Key"></param>
        public static void Encrypt(XmlDocument Doc, string ElementName, SymmetricAlgorithm Key)
        {
            // Check the arguments.
            if (Doc == null)
                throw new ArgumentNullException("Doc");
            if (ElementName == null)
                throw new ArgumentNullException("ElementToEncrypt");
            if (Key == null)
                throw new ArgumentNullException("Alg");

            ////////////////////////////////////////////////
            // Find the specified element in the XmlDocument
            // object and create a new XmlElemnt object.
            ////////////////////////////////////////////////
            XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementName)[0] as XmlElement;
            // Throw an XmlException if the element was not found.
            if (elementToEncrypt == null)
            {
                throw new XmlException("The specified element was not found");

            }

            //////////////////////////////////////////////////
            // Create a new instance of the EncryptedXml class
            // and use it to encrypt the XmlElement with the
            // symmetric key.
            //////////////////////////////////////////////////

            EncryptedXml eXml = new EncryptedXml();

            byte[] encryptedElement = eXml.EncryptData(elementToEncrypt, Key, false);
            ////////////////////////////////////////////////
            // Construct an EncryptedData object and populate
            // it with the desired encryption information.
            ////////////////////////////////////////////////

            EncryptedData edElement = new EncryptedData();
            edElement.Type = EncryptedXml.XmlEncElementUrl;

            // Create an EncryptionMethod element so that the
            // receiver knows which algorithm to use for decryption.
            // Determine what kind of algorithm is being used and
            // supply the appropriate URL to the EncryptionMethod element.

            string encryptionMethod = null;

            if (Key is TripleDES)
            {
                encryptionMethod = EncryptedXml.XmlEncTripleDESUrl;
            }
            else if (Key is DES)
            {
                encryptionMethod = EncryptedXml.XmlEncDESUrl;
            }
            if (Key is Rijndael)
            {
                switch (Key.KeySize)
                {
                    case 128:
                        encryptionMethod = EncryptedXml.XmlEncAES128Url;
                        break;
                    case 192:
                        encryptionMethod = EncryptedXml.XmlEncAES192Url;
                        break;
                    case 256:
                        encryptionMethod = EncryptedXml.XmlEncAES256Url;
                        break;
                }
            }
            else
            {
                // Throw an exception if the transform is not in the previous categories
                throw new CryptographicException("The specified algorithm is not supported for XML Encryption.");
            }

            edElement.EncryptionMethod = new EncryptionMethod(encryptionMethod);

            // Add the encrypted element data to the
            // EncryptedData object.
            edElement.CipherData.CipherValue = encryptedElement;

            ////////////////////////////////////////////////////
            // Replace the element from the original XmlDocument
            // object with the EncryptedData element.
            ////////////////////////////////////////////////////
            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
        }