Esempio n. 1
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));
			}
		}
        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 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);
        }
Esempio n. 4
0
		public void LoadXml ()
		{
			string xml = "<e:EncryptedKey xmlns:e='http://www.w3.org/2001/04/xmlenc#'><e:EncryptionMethod Algorithm='http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p'><DigestMethod xmlns='http://www.w3.org/2000/09/xmldsig#' /></e:EncryptionMethod><KeyInfo xmlns='http://www.w3.org/2000/09/xmldsig#'><o:SecurityTokenReference xmlns:o='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'><o:Reference URI='#uuid-8a013fe7-86f5-4c11-bf78-61674310679f-1' /></o:SecurityTokenReference></KeyInfo><e:CipherData><e:CipherValue>LSZFpnTv+vyB5iEdIAR2WGSz6MXF9KqONvkKaNhqLuSmhQ6F7xlqLHeoQjS2XoOTXUhkFcKNF/BUzdMSg9pElJX5hlQQqx7OQS9WAH4mSYG0SAn8wt5CStXf5yjQ5quizXJ/2+zgxnuTITwYR/FRi8L+0GLw6BOu8YaLSZyjZg8=</e:CipherValue></e:CipherData><e:ReferenceList><e:DataReference URI='#_1' /><e:DataReference URI='#_6' /></e:ReferenceList></e:EncryptedKey>";
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (xml);
			EncryptedKey ek = new EncryptedKey ();
			ek.LoadXml (doc.DocumentElement);
		}
        public static byte[] GetSecretKey(EncryptedKey encryptedKey, AsymmetricAlgorithm privateKey)
        {
            var keyAlgorithm = encryptedKey.EncryptionMethod.KeyAlgorithm;
            var asymmetricAlgorithm = GetAsymmetricKeyTransportAlgorithm(keyAlgorithm);
            asymmetricAlgorithm.FromXmlString(privateKey.ToXmlString(true));

            var useOaep = keyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl;
            return asymmetricAlgorithm.Decrypt(encryptedKey.CipherData.CipherValue, useOaep);
        }
        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;

        }
 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;
 }
Esempio n. 8
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);
        }
        public static EncryptedKey ToEncryptedKey(X509Certificate2 certificate, SymmetricAlgorithm key)
        {
            var provider = new RSACryptoServiceProvider();
            provider.FromXmlString(certificate.PublicKey.Key.ToXmlString(false));
            var secretKey = provider.Encrypt(key.Key, false);
            
            var encryptedKey = new EncryptedKey
            {
                EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSA15Url),
                CipherData = new CipherData(secretKey)
            };

            encryptedKey.KeyInfo.AddClause(new KeyInfoName("encryption"));
            
            return encryptedKey;
        }
        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);
        }
Esempio n. 11
0
        private Legacy.KeyInfoEncryptedKey EncryptKey(byte[] key, RSA encryptionKey, string method, Legacy.KeyInfoClause encryptionKeyInfoClause)
        {
            var encryptionKeyInfo = new Legacy.KeyInfo();

            encryptionKeyInfo.AddClause(encryptionKeyInfoClause);
            var cipherValue  = Legacy.EncryptedXml.EncryptKey(key, encryptionKey, true);
            var encryptedKey = new Legacy.EncryptedKey
            {
                CipherData = new Legacy.CipherData {
                    CipherValue = cipherValue
                },
                EncryptionMethod = new Legacy.EncryptionMethod(method),
                KeyInfo          = encryptionKeyInfo
            };

            return(new Legacy.KeyInfoEncryptedKey {
                EncryptedKey = encryptedKey
            });
        }
        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();
        }
Esempio n. 13
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;
        }
Esempio n. 14
0
        public override byte[] DecryptEncryptedKey(EncryptedKey encryptedKey)
        {
            if (encryptedKey == null)
            {
                throw new ArgumentNullException(nameof(encryptedKey));
            }

            if (encryptedKey.CipherData.CipherValue == null)
            {
                throw new NotImplementedException("Unable to decode CipherData of type \"CipherReference\".");
            }

            // use the key info
            if (privateKey == null)
            {
                return base.DecryptEncryptedKey(encryptedKey);
            }

            var useOaep = (encryptedKey.EncryptionMethod != null &&
                         encryptedKey.EncryptionMethod.KeyAlgorithm == XmlEncRSAOAEPUrl);

            return DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, useOaep);
        }
Esempio n. 15
0
        /// <summary>
        /// Extracts the key from a &lt;EncryptedKey&gt; element.
        /// </summary>
        /// <param name="encryptedKeyElement">The encrypted key element.</param>
        /// <param name="keyAlgorithm">The key algorithm.</param>
        /// <returns>The <see cref="SymmetricAlgorithm"/>.</returns>
        private SymmetricAlgorithm ToSymmetricKey(XmlElement encryptedKeyElement, string keyAlgorithm)
        {
            var encryptedKey = new EncryptedKey();
            encryptedKey.LoadXml(encryptedKeyElement);

            var useOaep = UseOaepDefault;
            if (encryptedKey.EncryptionMethod != null)
            {
                useOaep = encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl;
            }

            if (encryptedKey.CipherData.CipherValue != null)
            {
                var key = GetKeyInstance(keyAlgorithm);
                key.Key = EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, TransportKey, useOaep);

                return key;
            }
            
            throw new NotImplementedException("Unable to decode CipherData of type \"CipherReference\".");
        }
Esempio n. 16
0
 public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey)
 {
     if (encryptedKey == null)
     {
         throw new ArgumentNullException("encryptedKey");
     }
     if (encryptedKey.KeyInfo != null)
     {
         IEnumerator  enumerator = encryptedKey.KeyInfo.GetEnumerator();
         EncryptedKey key2       = null;
         bool         useOAEP    = false;
         while (enumerator.MoveNext())
         {
             KeyInfoName current = enumerator.Current as KeyInfoName;
             if (current != null)
             {
                 string str  = current.Value;
                 object obj2 = this.m_keyNameMapping[str];
                 if (obj2 != null)
                 {
                     if (obj2 is SymmetricAlgorithm)
                     {
                         return(DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)obj2));
                     }
                     useOAEP = (encryptedKey.EncryptionMethod != null) && (encryptedKey.EncryptionMethod.KeyAlgorithm == "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p");
                     return(DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)obj2, useOAEP));
                 }
                 break;
             }
             KeyInfoX509Data data = enumerator.Current as KeyInfoX509Data;
             if (data != null)
             {
                 X509Certificate2Enumerator enumerator2 = System.Security.Cryptography.Xml.Utils.BuildBagOfCerts(data, CertUsageType.Decryption).GetEnumerator();
                 while (enumerator2.MoveNext())
                 {
                     RSA privateKey = enumerator2.Current.PrivateKey as RSA;
                     if (privateKey != null)
                     {
                         useOAEP = (encryptedKey.EncryptionMethod != null) && (encryptedKey.EncryptionMethod.KeyAlgorithm == "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p");
                         return(DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, useOAEP));
                     }
                 }
                 break;
             }
             KeyInfoRetrievalMethod method = enumerator.Current as KeyInfoRetrievalMethod;
             if (method != null)
             {
                 string idValue = System.Security.Cryptography.Xml.Utils.ExtractIdFromLocalUri(method.Uri);
                 key2 = new EncryptedKey();
                 key2.LoadXml(this.GetIdElement(this.m_document, idValue));
                 return(this.DecryptEncryptedKey(key2));
             }
             KeyInfoEncryptedKey key = enumerator.Current as KeyInfoEncryptedKey;
             if (key != null)
             {
                 key2 = key.EncryptedKey;
                 byte[] buffer = this.DecryptEncryptedKey(key2);
                 if (buffer != null)
                 {
                     SymmetricAlgorithm symmetricAlgorithm = (SymmetricAlgorithm)CryptoConfig.CreateFromName(encryptedKey.EncryptionMethod.KeyAlgorithm);
                     symmetricAlgorithm.Key = buffer;
                     return(DecryptKey(encryptedKey.CipherData.CipherValue, symmetricAlgorithm));
                 }
             }
         }
     }
     return(null);
 }
Esempio n. 17
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);
        }
Esempio n. 18
0
 public KeyInfoEncryptedKey (EncryptedKey encryptedKey) {
     m_encryptedKey = encryptedKey;
 }
        private static XmlDocument EncryptXmlDocument(XmlDocument xmlDocument, IEnumerable<X509Certificate2> certificates)
        {
            // Создание объекта для шифрации XML
            var encryptedXml = new GostEncryptedXml();

            // Поиск элементов для шифрации
            var elements = xmlDocument.SelectNodes("//SomeElement[@Encrypt='true']");

            if (elements != null)
            {
                var elementIndex = 0;

                foreach (XmlElement element in elements)
                {
                    // Формирование элемента EncryptedData
                    var elementEncryptedData = new EncryptedData();
                    elementEncryptedData.Id = "EncryptedElement" + elementIndex++;
                    elementEncryptedData.Type = EncryptedXml.XmlEncElementUrl;
                    elementEncryptedData.EncryptionMethod = new EncryptionMethod(GostEncryptedXml.XmlEncGost28147Url);
                    elementEncryptedData.KeyInfo = new KeyInfo();

                    using (var sessionKey = new Gost28147SymmetricAlgorithm())
                    {
                        // Шифрация элемента с использованием симметричного ключа
                        var encryptedElement = encryptedXml.EncryptData(element, sessionKey, false);

                        foreach (var certificate in certificates)
                        {
                            // Шифрация сессионного ключа с использованием открытого ключа сертификата
                            var encryptedSessionKeyData = GostEncryptedXml.EncryptKey(sessionKey, (Gost3410AsymmetricAlgorithmBase)certificate.GetPublicKeyAlgorithm());

                            // Формирование информации о зашифрованном сессионном ключе
                            var encryptedSessionKey = new EncryptedKey();
                            encryptedSessionKey.CipherData = new CipherData(encryptedSessionKeyData);
                            encryptedSessionKey.EncryptionMethod = new EncryptionMethod(GostEncryptedXml.XmlEncGostCryptoProKeyExportUrl);
                            encryptedSessionKey.AddReference(new DataReference { Uri = "#" + elementEncryptedData.Id });
                            encryptedSessionKey.KeyInfo.AddClause(new KeyInfoX509Data(certificate));

                            // Добавление ссылки на зашифрованный ключ, используемый при шифровании данных
                            elementEncryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedSessionKey));
                        }

                        // Установка зашифрованных данных у объекта EncryptedData
                        elementEncryptedData.CipherData.CipherValue = encryptedElement;
                    }

                    // Замена элемента его зашифрованным представлением
                    GostEncryptedXml.ReplaceElement(element, elementEncryptedData, false);
                }
            }

            return xmlDocument;
        }
Esempio n. 20
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;
        }
		public EncryptedData Encrypt (XmlElement inputElement, string keyName)
		{
			// There are two keys of note here.
			// 1) KeyAlg: the key-encryption-key is used to wrap a key.  The keyName
			//    parameter will give us the KEK.
			// 2) SymAlg: A 256-bit AES key will be generated to encrypt the contents.
			//    This key will be wrapped using the KEK.

			SymmetricAlgorithm symAlg = SymmetricAlgorithm.Create ("Rijndael");
			symAlg.KeySize = 256;
			symAlg.GenerateKey ();
			symAlg.GenerateIV ();

			EncryptedData encryptedData = new EncryptedData ();
			EncryptedKey encryptedKey = new EncryptedKey();

			object keyAlg = keyNameMapping [keyName];

			encryptedKey.EncryptionMethod = new EncryptionMethod (GetKeyWrapAlgorithmUri (keyAlg));

			if (keyAlg is RSA)
				encryptedKey.CipherData = new CipherData (EncryptKey (symAlg.Key, (RSA) keyAlg, false));
			else
				encryptedKey.CipherData = new CipherData (EncryptKey (symAlg.Key, (SymmetricAlgorithm) keyAlg));

			encryptedKey.KeyInfo = new KeyInfo();
			encryptedKey.KeyInfo.AddClause (new KeyInfoName (keyName));
			
			encryptedData.Type = XmlEncElementUrl;
			encryptedData.EncryptionMethod = new EncryptionMethod (GetAlgorithmUri (symAlg));
			encryptedData.KeyInfo = new KeyInfo ();
			encryptedData.KeyInfo.AddClause (new KeyInfoEncryptedKey (encryptedKey));
			encryptedData.CipherData = new CipherData (EncryptData (inputElement, symAlg, false));

			return encryptedData;
		}
		public virtual byte[] DecryptEncryptedKey (EncryptedKey encryptedKey)
		{
			object keyAlg = null;
			foreach (KeyInfoClause innerClause in encryptedKey.KeyInfo) {
				if (innerClause is KeyInfoName) {
					keyAlg = keyNameMapping [((KeyInfoName) innerClause).Value];
					break;
				}
			}
			switch (encryptedKey.EncryptionMethod.KeyAlgorithm) {
			case XmlEncRSA15Url:
				return DecryptKey (encryptedKey.CipherData.CipherValue, (RSA) keyAlg, false);
			case XmlEncRSAOAEPUrl:
				return DecryptKey (encryptedKey.CipherData.CipherValue, (RSA) keyAlg, true);
			}
			return DecryptKey (encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm) keyAlg);
		}
Esempio n. 23
0
 public override void LoadXml(XmlElement value)
 {
     _encryptedKey = new EncryptedKey();
     _encryptedKey.LoadXml(value);
 }
Esempio n. 24
0
 public KeyInfoEncryptedKey(EncryptedKey encryptedKey)
 {
     _encryptedKey = encryptedKey;
 }
Esempio n. 25
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);
        }
        private static XmlDocument EncryptXmlDocument(XmlDocument xmlDocument, Gost3410AsymmetricAlgorithmBase publicKey)
        {
            // Создание объекта для шифрации XML
            var encryptedXml = new GostEncryptedXml();

            // Поиск элементов для шифрации
            var elements = xmlDocument.SelectNodes("//SomeElement[@Encrypt='true']");

            if (elements != null)
            {
                var elementIndex = 0;

                foreach (XmlElement element in elements)
                {
                    // Создание случайного сессионного ключа
                    using (var sessionKey = new Gost28147SymmetricAlgorithm())
                    {
                        // Шифрация элемента
                        var encryptedData = encryptedXml.EncryptData(element, sessionKey, false);

                        // Шифрация сессионного ключа с использованием публичного асимметричного ключа
                        var encryptedSessionKeyData = GostEncryptedXml.EncryptKey(sessionKey, publicKey);

                        // Формирование элемента EncryptedData
                        var elementEncryptedData = new EncryptedData();
                        elementEncryptedData.Id = "EncryptedElement" + elementIndex++;
                        elementEncryptedData.Type = EncryptedXml.XmlEncElementUrl;
                        elementEncryptedData.EncryptionMethod = new EncryptionMethod(GostEncryptedXml.XmlEncGost28147Url);
                        elementEncryptedData.CipherData.CipherValue = encryptedData;
                        elementEncryptedData.KeyInfo = new KeyInfo();

                        // Формирование информации о зашифрованном сессионном ключе
                        var encryptedSessionKey = new EncryptedKey();
                        encryptedSessionKey.CipherData = new CipherData(encryptedSessionKeyData);
                        encryptedSessionKey.EncryptionMethod = new EncryptionMethod(GostEncryptedXml.XmlEncGostKeyTransportUrl);
                        encryptedSessionKey.AddReference(new DataReference { Uri = "#" + elementEncryptedData.Id });
                        encryptedSessionKey.KeyInfo.AddClause(new KeyInfoName { Value = "KeyName1" });

                        // Добавление ссылки на зашифрованный ключ, используемый при шифровании данных
                        elementEncryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedSessionKey));

                        // Замена элемента его зашифрованным представлением
                        GostEncryptedXml.ReplaceElement(element, elementEncryptedData, false);
                    }
                }
            }

            return xmlDocument;
        }
Esempio n. 27
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;
        }
Esempio n. 28
0
 public KeyInfoEncryptedKey(EncryptedKey ek)
 {
     EncryptedKey = ek;
 }
Esempio n. 29
0
        // Try to decrypt the EncryptedKey given the key mapping
        public virtual byte[] DecryptEncryptedKey (EncryptedKey encryptedKey) {
            if (encryptedKey == null)
                throw new ArgumentNullException("encryptedKey");
            if (encryptedKey.KeyInfo == null)
                return null;

            IEnumerator keyInfoEnum = encryptedKey.KeyInfo.GetEnumerator();
            KeyInfoName kiName;
            KeyInfoX509Data kiX509Data;
            KeyInfoRetrievalMethod kiRetrievalMethod;
            KeyInfoEncryptedKey kiEncKey;
            EncryptedKey ek = null;
            bool fOAEP = false;

            while (keyInfoEnum.MoveNext()) {
                kiName = keyInfoEnum.Current as KeyInfoName;
                if (kiName != null) {
                    // Get the decryption key from the key mapping
                    string keyName = kiName.Value;
                    Object kek = m_keyNameMapping[keyName];
                    if (kek != null) {
                        // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table
                        if (kek is SymmetricAlgorithm)
                            return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm) kek);

                        // kek is an RSA key: get fOAEP from the algorithm, default to false
                        fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl);
                        return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA) kek, fOAEP);
                    }
                    break;
                }
                kiX509Data = keyInfoEnum.Current as KeyInfoX509Data;
                if (kiX509Data != null) {
                    X509Certificate2Collection collection = Utils.BuildBagOfCerts(kiX509Data, CertUsageType.Decryption);
                    foreach (X509Certificate2 certificate in collection) {
                        RSA privateKey = certificate.PrivateKey as RSA;
                        if (privateKey != null) {
                            fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl);
                            return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, fOAEP);
                        }
                    }
                    break;
                }
                kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
                if (kiRetrievalMethod != null) {
                    string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri);
                    ek = new EncryptedKey();
                    ek.LoadXml(GetIdElement(m_document, idref));
                    try {
                        //Following checks if XML dsig processing is in loop and within the limit defined by machine
                        // admin or developer. Once the recursion depth crosses the defined limit it will throw exception.
                        m_xmlDsigSearchDepthCounter++;
                        if (IsOverXmlDsigRecursionLimit()) {
                            //Throw exception once recursion limit is hit. 
                            throw new CryptoSignedXmlRecursionException();
                        }
                        else {
                            return DecryptEncryptedKey(ek);
                        }
                    }
                    finally {
                        m_xmlDsigSearchDepthCounter--;
                    }
                }
                kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
                if (kiEncKey != null) {
                    ek = kiEncKey.EncryptedKey;
                    // recursively process EncryptedKey elements
                    byte[] encryptionKey = DecryptEncryptedKey(ek);
                    if (encryptionKey != null) {
                        // this is a symmetric algorithm for sure
                        SymmetricAlgorithm symAlg = (SymmetricAlgorithm) CryptoConfig.CreateFromName(encryptedKey.EncryptionMethod.KeyAlgorithm);
                        symAlg.Key = encryptionKey;
                        return EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, symAlg);
                    }
                }
            }
            return null;
        }
        public override SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri)
        {
            if (encryptedData == null)
            {
                throw ExceptionUtility.ArgumentNull("encryptedData");
            }

            SymmetricAlgorithm decryptionKey = null;

            if (encryptedData.KeyInfo != null)
            {
                EncryptedKey encryptedKey = null;

                foreach (var keyInfo in encryptedData.KeyInfo)
                {
                    // Извлечение ключа по имени
                    if (keyInfo is KeyInfoName)
                    {
                        var keyName = ((KeyInfoName)keyInfo).Value;
                        var keyAlgorithm = KeyNameMapping[keyName];

                        if (keyAlgorithm == null)
                        {
                            var nsManager = new XmlNamespaceManager(Document.NameTable);
                            nsManager.AddNamespace("enc", XmlEncNamespaceUrl);

                            var encryptedKeyNodes = Document.SelectNodes("//enc:EncryptedKey", nsManager);

                            if (encryptedKeyNodes != null)
                            {
                                foreach (XmlElement encryptedKeyNode in encryptedKeyNodes)
                                {
                                    var currentEncryptedKey = new EncryptedKey();
                                    currentEncryptedKey.LoadXml(encryptedKeyNode);

                                    if ((currentEncryptedKey.CarriedKeyName == keyName) && (currentEncryptedKey.Recipient == Recipient))
                                    {
                                        encryptedKey = currentEncryptedKey;
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            decryptionKey = (SymmetricAlgorithm)keyAlgorithm;
                        }

                        break;
                    }

                    // Извлечение ключа по ссылке
                    if (keyInfo is KeyInfoRetrievalMethod)
                    {
                        var idValue = GostXmlUtils.ExtractIdFromLocalUri(((KeyInfoRetrievalMethod)keyInfo).Uri);
                        var idElement = GetIdElement(Document, idValue);

                        if (idElement != null)
                        {
                            encryptedKey = new EncryptedKey();
                            encryptedKey.LoadXml(idElement);
                        }

                        break;
                    }

                    // Ключ в готовом виде
                    if (keyInfo is KeyInfoEncryptedKey)
                    {
                        encryptedKey = ((KeyInfoEncryptedKey)keyInfo).EncryptedKey;
                        break;
                    }
                }

                if (decryptionKey == null && encryptedKey != null)
                {
                    if (symmetricAlgorithmUri == null)
                    {
                        if (encryptedData.EncryptionMethod == null)
                        {
                            throw ExceptionUtility.CryptographicException(Resources.XmlMissingAlgorithm);
                        }

                        symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
                    }

                    decryptionKey = DecryptEncryptedKeyClass(encryptedKey, symmetricAlgorithmUri);
                }
            }

            return decryptionKey;
        }
Esempio n. 31
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;
        }
        private SymmetricAlgorithm DecryptEncryptedKeyClass(EncryptedKey encryptedKey, string symmetricAlgorithmUri)
        {
            if (encryptedKey == null)
            {
                throw ExceptionUtility.ArgumentNull("encryptedKey");
            }

            SymmetricAlgorithm decryptionKey = null;

            if (encryptedKey.KeyInfo != null)
            {
                foreach (var keyInfo in encryptedKey.KeyInfo)
                {
                    // Извлечение ключа по имени
                    if (keyInfo is KeyInfoName)
                    {
                        var keyName = ((KeyInfoName)keyInfo).Value;
                        var keyAlgorithm = KeyNameMapping[keyName];

                        if (keyAlgorithm != null)
                        {
                            if (keyAlgorithm is SymmetricAlgorithm)
                            {
                                decryptionKey = DecryptKeyClass(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)keyAlgorithm, symmetricAlgorithmUri, encryptedKey.EncryptionMethod.KeyAlgorithm);
                            }
                            else if (keyAlgorithm is RSA)
                            {
                                var useOaep = (encryptedKey.EncryptionMethod != null) && (encryptedKey.EncryptionMethod.KeyAlgorithm == XmlEncRSAOAEPUrl);
                                decryptionKey = DecryptKeyClass(encryptedKey.CipherData.CipherValue, (RSA)keyAlgorithm, useOaep, symmetricAlgorithmUri);
                            }
                            else if (keyAlgorithm is Gost3410AsymmetricAlgorithmBase)
                            {
                                decryptionKey = DecryptKeyClass(encryptedKey.CipherData.CipherValue, (Gost3410AsymmetricAlgorithmBase)keyAlgorithm);
                            }
                        }

                        break;
                    }

                    // Извлечение ключа из сертификата
                    if (keyInfo is KeyInfoX509Data)
                    {
                        var certificates = GostXmlUtils.BuildBagOfCertsDecryption((KeyInfoX509Data)keyInfo);

                        foreach (var certificate in certificates)
                        {
                            var privateKey = certificate.GetPrivateKeyAlgorithm();

                            if (privateKey is RSA)
                            {
                                var useOaep = (encryptedKey.EncryptionMethod != null) && (encryptedKey.EncryptionMethod.KeyAlgorithm == XmlEncRSAOAEPUrl);
                                decryptionKey = DecryptKeyClass(encryptedKey.CipherData.CipherValue, (RSA)privateKey, useOaep, symmetricAlgorithmUri);
                            }
                            else if (privateKey is Gost3410AsymmetricAlgorithmBase)
                            {
                                decryptionKey = DecryptKeyClass(encryptedKey.CipherData.CipherValue, (Gost3410AsymmetricAlgorithmBase)privateKey);
                            }
                        }

                        break;
                    }

                    // Извлечение ключа по ссылке
                    if (keyInfo is KeyInfoRetrievalMethod)
                    {
                        var idValue = GostXmlUtils.ExtractIdFromLocalUri(((KeyInfoRetrievalMethod)keyInfo).Uri);
                        var idElement = GetIdElement(Document, idValue);

                        if (idElement != null)
                        {
                            var secondEncryptedKey = new EncryptedKey();
                            secondEncryptedKey.LoadXml(idElement);

                            decryptionKey = DecryptEncryptedKeyClass(secondEncryptedKey, symmetricAlgorithmUri);
                        }

                        break;
                    }

                    // Ключ в готовом виде
                    if (keyInfo is KeyInfoEncryptedKey)
                    {
                        var secondEncryptedKey = ((KeyInfoEncryptedKey)keyInfo).EncryptedKey;
                        var symmetricAlgorithm = DecryptEncryptedKeyClass(secondEncryptedKey, symmetricAlgorithmUri);

                        if (symmetricAlgorithm != null)
                        {
                            decryptionKey = DecryptKeyClass(encryptedKey.CipherData.CipherValue, symmetricAlgorithm, symmetricAlgorithmUri, encryptedKey.EncryptionMethod.KeyAlgorithm);
                        }

                        break;
                    }
                }
            }

            return decryptionKey;
        }
Esempio n. 33
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));
			}
		}
Esempio n. 34
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(nameof(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)_keyNameMapping[keyName] != null)
                    {
                        return((SymmetricAlgorithm)_keyNameMapping[keyName]);
                    }
                    // try to get it from a CarriedKeyName
                    XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable);
                    nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
                    XmlNodeList encryptedKeyList = _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 == 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(_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(SR.Cryptography_Xml_MissingAlgorithm);
                    }
                    symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
                }
                byte[] key = DecryptEncryptedKey(ek);
                if (key == null)
                {
                    throw new CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey);
                }

                SymmetricAlgorithm symAlg = CryptoHelpers.CreateFromName <SymmetricAlgorithm>(symmetricAlgorithmUri);
                if (symAlg == null)
                {
                    throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
                }
                symAlg.Key = key;
                return(symAlg);
            }
            return(null);
        }
Esempio n. 35
0
 public override void LoadXml(XmlElement value) {
     m_encryptedKey = new EncryptedKey();
     m_encryptedKey.LoadXml(value);
 }
Esempio n. 36
0
        // Try to decrypt the EncryptedKey given the key mapping
        public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey)
        {
            if (encryptedKey == null)
            {
                throw new ArgumentNullException(nameof(encryptedKey));
            }
            if (encryptedKey.KeyInfo == null)
            {
                return(null);
            }

            IEnumerator            keyInfoEnum = encryptedKey.KeyInfo.GetEnumerator();
            KeyInfoName            kiName;
            KeyInfoX509Data        kiX509Data;
            KeyInfoRetrievalMethod kiRetrievalMethod;
            KeyInfoEncryptedKey    kiEncKey;
            EncryptedKey           ek = null;
            bool fOAEP = false;

            while (keyInfoEnum.MoveNext())
            {
                kiName = keyInfoEnum.Current as KeyInfoName;
                if (kiName != null)
                {
                    // Get the decryption key from the key mapping
                    string keyName = kiName.Value;
                    object kek     = _keyNameMapping[keyName];
                    if (kek != null)
                    {
                        if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null)
                        {
                            throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
                        }
                        // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table
                        if (kek is SymmetricAlgorithm)
                        {
                            return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)kek));
                        }

                        // kek is an RSA key: get fOAEP from the algorithm, default to false
                        fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl);
                        return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)kek, fOAEP));
                    }
                    break;
                }
                kiX509Data = keyInfoEnum.Current as KeyInfoX509Data;
                if (kiX509Data != null)
                {
                    X509Certificate2Collection collection = Utils.BuildBagOfCerts(kiX509Data, CertUsageType.Decryption);
                    foreach (X509Certificate2 certificate in collection)
                    {
                        using (RSA privateKey = certificate.GetRSAPrivateKey())
                        {
                            if (privateKey != null)
                            {
                                if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null)
                                {
                                    throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
                                }
                                fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl);
                                return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, fOAEP));
                            }
                        }
                    }
                    break;
                }
                kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
                if (kiRetrievalMethod != null)
                {
                    string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri);
                    ek = new EncryptedKey();
                    ek.LoadXml(GetIdElement(_document, idref));
                    try
                    {
                        //Following checks if XML dsig processing is in loop and within the limit defined by machine
                        // admin or developer. Once the recursion depth crosses the defined limit it will throw exception.
                        _xmlDsigSearchDepthCounter++;
                        if (IsOverXmlDsigRecursionLimit())
                        {
                            //Throw exception once recursion limit is hit.
                            throw new CryptoSignedXmlRecursionException();
                        }
                        else
                        {
                            return(DecryptEncryptedKey(ek));
                        }
                    }
                    finally
                    {
                        _xmlDsigSearchDepthCounter--;
                    }
                }
                kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
                if (kiEncKey != null)
                {
                    ek = kiEncKey.EncryptedKey;
                    // recursively process EncryptedKey elements
                    byte[] encryptionKey = DecryptEncryptedKey(ek);
                    if (encryptionKey != null)
                    {
                        // this is a symmetric algorithm for sure
                        SymmetricAlgorithm symAlg = CryptoHelpers.CreateFromName <SymmetricAlgorithm>(encryptedKey.EncryptionMethod.KeyAlgorithm);
                        if (symAlg == null)
                        {
                            throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
                        }
                        symAlg.Key = encryptionKey;
                        if (encryptedKey.CipherData == null || encryptedKey.CipherData.CipherValue == null)
                        {
                            throw new CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
                        }
                        symAlg.Key = encryptionKey;
                        return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, symAlg));
                    }
                }
            }
            return(null);
        }
Esempio n. 37
0
        public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri)
        {
            if (encryptedData == null)
            {
                throw new ArgumentNullException("encryptedData");
            }
            if (encryptedData.KeyInfo == null)
            {
                return(null);
            }
            IEnumerator  enumerator   = encryptedData.KeyInfo.GetEnumerator();
            EncryptedKey encryptedKey = null;

            while (enumerator.MoveNext())
            {
                KeyInfoName current = enumerator.Current as KeyInfoName;
                if (current != null)
                {
                    string str = current.Value;
                    if (((SymmetricAlgorithm)this.m_keyNameMapping[str]) != null)
                    {
                        return((SymmetricAlgorithm)this.m_keyNameMapping[str]);
                    }
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(this.m_document.NameTable);
                    nsmgr.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#");
                    XmlNodeList list = this.m_document.SelectNodes("//enc:EncryptedKey", nsmgr);
                    if (list != null)
                    {
                        foreach (XmlNode node in list)
                        {
                            XmlElement   element = node as XmlElement;
                            EncryptedKey key3    = new EncryptedKey();
                            key3.LoadXml(element);
                            if ((key3.CarriedKeyName == str) && (key3.Recipient == this.Recipient))
                            {
                                encryptedKey = key3;
                                break;
                            }
                        }
                    }
                    break;
                }
                KeyInfoRetrievalMethod method = enumerator.Current as KeyInfoRetrievalMethod;
                if (method != null)
                {
                    string idValue = System.Security.Cryptography.Xml.Utils.ExtractIdFromLocalUri(method.Uri);
                    encryptedKey = new EncryptedKey();
                    encryptedKey.LoadXml(this.GetIdElement(this.m_document, idValue));
                    break;
                }
                KeyInfoEncryptedKey key = enumerator.Current as KeyInfoEncryptedKey;
                if (key != null)
                {
                    encryptedKey = key.EncryptedKey;
                    break;
                }
            }
            if (encryptedKey == null)
            {
                return(null);
            }
            if (symmetricAlgorithmUri == null)
            {
                if (encryptedData.EncryptionMethod == null)
                {
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingAlgorithm"));
                }
                symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
            }
            byte[] buffer = this.DecryptEncryptedKey(encryptedKey);
            if (buffer == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingDecryptionKey"));
            }
            SymmetricAlgorithm algorithm = (SymmetricAlgorithm)CryptoConfig.CreateFromName(symmetricAlgorithmUri);

            algorithm.Key = buffer;
            return(algorithm);
        }
Esempio n. 38
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(nameof(inputElement));
            }
            if (keyName == null)
            {
                throw new ArgumentNullException(nameof(keyName));
            }

            object encryptionKey = null;

            if (_keyNameMapping != null)
            {
                encryptionKey = _keyNameMapping[keyName];
            }

            if (encryptionKey == null)
            {
                throw new CryptographicException(SR.Cryptography_Xml_MissingEncryptionKey);
            }

            // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table
            SymmetricAlgorithm symKey = encryptionKey as SymmetricAlgorithm;
            RSA rsa = encryptionKey as RSA;

            // Create the EncryptedData object, using an AES-256 session key by default.
            EncryptedData ed = new EncryptedData();

            ed.Type             = EncryptedXml.XmlEncElementUrl;
            ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);

            // Include the key name in the EncryptedKey KeyInfo.
            string encryptionMethod = null;

            if (symKey == null)
            {
                encryptionMethod = EncryptedXml.XmlEncRSA15Url;
            }
            else if (symKey is TripleDES)
            {
                // CMS Triple DES Key Wrap
                encryptionMethod = EncryptedXml.XmlEncTripleDESKeyWrapUrl;
            }
            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(SR.Cryptography_Xml_NotSupportedCryptographicTransform);
            }
            EncryptedKey ek = new EncryptedKey();

            ek.EncryptionMethod = new EncryptionMethod(encryptionMethod);
            ek.KeyInfo.AddClause(new KeyInfoName(keyName));

            // Create a random AES session key and encrypt it with the public key associated with the certificate.
            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);
        }
Esempio n. 39
0
        public EncryptedData Encrypt(XmlElement inputElement, string keyName)
        {
            if (inputElement == null)
            {
                throw new ArgumentNullException("inputElement");
            }
            if (keyName == null)
            {
                throw new ArgumentNullException("keyName");
            }
            object obj2 = null;

            if (this.m_keyNameMapping != null)
            {
                obj2 = this.m_keyNameMapping[keyName];
            }
            if (obj2 == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingEncryptionKey"));
            }
            SymmetricAlgorithm symmetricAlgorithm = obj2 as SymmetricAlgorithm;
            RSA           rsa  = obj2 as RSA;
            EncryptedData data = new EncryptedData {
                Type             = "http://www.w3.org/2001/04/xmlenc#Element",
                EncryptionMethod = new EncryptionMethod("http://www.w3.org/2001/04/xmlenc#aes256-cbc")
            };
            string algorithm = null;

            if (symmetricAlgorithm == null)
            {
                algorithm = "http://www.w3.org/2001/04/xmlenc#rsa-1_5";
            }
            else if (symmetricAlgorithm is TripleDES)
            {
                algorithm = "http://www.w3.org/2001/04/xmlenc#kw-tripledes";
            }
            else
            {
                if (!(symmetricAlgorithm is Rijndael) && !(symmetricAlgorithm is Aes))
                {
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_NotSupportedCryptographicTransform"));
                }
                switch (symmetricAlgorithm.KeySize)
                {
                case 0x80:
                    algorithm = "http://www.w3.org/2001/04/xmlenc#kw-aes128";
                    break;

                case 0xc0:
                    algorithm = "http://www.w3.org/2001/04/xmlenc#kw-aes192";
                    break;

                case 0x100:
                    algorithm = "http://www.w3.org/2001/04/xmlenc#kw-aes256";
                    break;
                }
            }
            EncryptedKey encryptedKey = new EncryptedKey {
                EncryptionMethod = new EncryptionMethod(algorithm)
            };

            encryptedKey.KeyInfo.AddClause(new KeyInfoName(keyName));
            RijndaelManaged managed = new RijndaelManaged();

            encryptedKey.CipherData.CipherValue = (symmetricAlgorithm == null) ? EncryptKey(managed.Key, rsa, false) : EncryptKey(managed.Key, symmetricAlgorithm);
            KeyInfoEncryptedKey clause = new KeyInfoEncryptedKey(encryptedKey);

            data.KeyInfo.AddClause(clause);
            data.CipherData.CipherValue = this.EncryptData(inputElement, managed, false);
            return(data);
        }
Esempio n. 40
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();
                }

            }

        }
        public new EncryptedData Encrypt(XmlElement element, X509Certificate2 certificate)
        {
            if (element == null)
            {
                return base.Encrypt(element, certificate);
            }

            if (certificate == null)
            {
                return base.Encrypt(element, certificate);
            }

            if (!string.Equals(certificate.PublicKey.Oid.Value, GostCryptoConfig.DefaultSignOid, StringComparison.OrdinalIgnoreCase))
            {
                return base.Encrypt(element, certificate);
            }

            var encryptedKey = new EncryptedKey
                               {
                                   EncryptionMethod = new EncryptionMethod(GostEncryptedXml.XmlEncGostKeyTransportUrl)
                               };

            encryptedKey.KeyInfo.AddClause(new KeyInfoX509Data(certificate));

            var encriptionKey = new Gost28147SymmetricAlgorithm();
            var publicKey = certificate.GetPublicKeyAlgorithm();
            encryptedKey.CipherData.CipherValue = EncryptKey(encriptionKey, publicKey as Gost3410AsymmetricAlgorithmBase);

            var encryptedData = new EncryptedData
                                {
                                    Type = XmlEncElementUrl,
                                    EncryptionMethod = new EncryptionMethod(GostEncryptedXml.XmlEncGost28147Url)
                                };

            encryptedData.KeyInfo.AddClause(new KeyInfoEncryptedKey(encryptedKey));
            encryptedData.CipherData.CipherValue = EncryptData(element, encriptionKey, false);

            return encryptedData;
        }
Esempio n. 42
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;
        }