Exemple #1
0
        public string GetEncryptionAlgorithm()
        {
            string xpath = ".//*[local-name()='EncryptionMethod']";

            var node = _encryptedKey.GetXml().SelectSingleNode(xpath) as XmlElement;

            return(node?.GetAttribute("Algorithm"));
        }
        public XmlElement DecryptSingleElementByKeyNumber(int encryptedKeyNumber)
        {
            EncryptedKey encryptedKey = new EncryptedKey();

            encryptedKey.LoadXml((XmlElement)this._encryptedKeyElements[encryptedKeyNumber]);
            ReferenceList      referenceList      = encryptedKey.ReferenceList;
            EncryptedReference encryptedReference = referenceList.Item(0);
            string             uri     = encryptedReference.Uri;
            KeyInfo            keyInfo = encryptedKey.KeyInfo;

            this._referenceList.Clear();
            ArrayList referenceElementList = new ArrayList();

            referenceElementList = this.FindXmlElementByURI(uri, this._tempdocument.ChildNodes[1]);
            XmlElement keyInfoElement = this._tempdocument.CreateElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl);

            keyInfoElement.AppendChild(_tempdocument.ImportNode((XmlNode)encryptedKey.GetXml(), true));
            XmlElement encryptedDataElement   = (XmlElement)referenceElementList[0];
            RSACryptoServiceProvider provider = this._webService.RSACryptoServiceProvider;
            EncryptedXml             encXml   = new EncryptedXml(this._tempdocument);

            encXml.AddKeyNameMapping("Web Service Public Key", provider);
            EncryptedData data = new EncryptedData();

            data.LoadXml((XmlElement)encryptedDataElement);
            SymmetricAlgorithm algo = SymmetricAlgorithm.Create();

            algo.Key = encXml.DecryptEncryptedKey(encryptedKey);
            byte[] t = encXml.DecryptData(data, algo);
            encXml.ReplaceData(encryptedDataElement, t);
            this._tempdocument.GetElementsByTagName("wsse:Security")[0].RemoveChild(_tempdocument.GetElementsByTagName("xenc:EncryptedKey")[0]);
            XmlElement root = (XmlElement)this._decryptedDataList[encryptedKeyNumber];

            return((XmlElement)root);
        }
        public void GetDecryptionKey_CarriedKeyName()
        {
            using (Aes aes = Aes.Create())
                using (Aes innerAes = Aes.Create())
                {
                    innerAes.KeySize = 128;

                    EncryptedData edata = new EncryptedData();
                    edata.KeyInfo = new KeyInfo();
                    edata.KeyInfo.AddClause(new KeyInfoName("aes"));

                    EncryptedKey ekey        = new EncryptedKey();
                    byte[]       encKeyBytes = EncryptedXml.EncryptKey(innerAes.Key, aes);
                    ekey.CipherData       = new CipherData(encKeyBytes);
                    ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
                    ekey.CarriedKeyName   = "aes";
                    ekey.KeyInfo          = new KeyInfo();
                    ekey.KeyInfo.AddClause(new KeyInfoName("another_aes"));

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(ekey.GetXml().OuterXml);

                    EncryptedXml exml = new EncryptedXml(doc);
                    exml.AddKeyNameMapping("another_aes", aes);
                    SymmetricAlgorithm decryptedAlg = exml.GetDecryptionKey(edata, EncryptedXml.XmlEncAES256Url);

                    Assert.Equal(innerAes.Key, decryptedAlg.Key);
                }
        }
Exemple #4
0
        private static string GetDigestAlgorithm(EncryptedKey encryptedKey)
        {
            string xpath      = $".//*[local-name()='EncryptionMethod']/*[local-name()='DigestMethod' and namespace-uri()='{Constants.Namespaces.XmlDsig}']";
            var    digestNode = encryptedKey.GetXml().SelectSingleNode(xpath) as XmlElement;

            return(digestNode?.GetAttribute("Algorithm"));
        }
Exemple #5
0
        public void Encrypt()
        {
            var encryptionAlgorithm = new AesGcm {
                KeySize = 128
            };

            encryptionAlgorithm.GenerateKey();

            byte[] encryptedSymmetricKey = RsaOaepSha256.Encrypt(encryptionAlgorithm.Key, PublicKeyInAsn1Format);

            var encryptedKey = new EncryptedKey
            {
                Id = "ek-" + Guid.NewGuid(),
                EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncRSAOAEPUrl),
                CipherData       = new CipherData
                {
                    CipherValue = encryptedSymmetricKey
                }
            };

            var encryptedDataList = new List <EncryptedData>();

            foreach (Attachment attachment in Attachments)
            {
                attachment.Stream.Position = 0;
                Stream encryptedStream = new MemoryStream();
                encryptedStream.Write(encryptionAlgorithm.IV, 0, encryptionAlgorithm.IV.Length);

                var cryptoStream = new CryptoStream(encryptedStream, encryptionAlgorithm.CreateEncryptor(), CryptoStreamMode.Write);
                attachment.Stream.CopyTo(cryptoStream);
                cryptoStream.FlushFinalBlock();
                attachment.Stream = encryptedStream;

                var encryptedData = new EncryptedData
                {
                    Id               = "ed-" + Guid.NewGuid(),
                    Type             = "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Only",
                    EncryptionMethod = new EncryptionMethod("http://www.w3.org/2009/xmlenc11#aes128-gcm"),
                    CipherData       = new CipherData
                    {
                        CipherReference = new CipherReference("cid:" + attachment.ContentId)
                    }
                };
                encryptedData.KeyInfo.AddClause(new SecurityTokenReference(encryptedKey.Id));
                encryptedData.CipherData.CipherReference.TransformChain.Add(new AttachmentCiphertextTransform());

                encryptedDataList.Add(encryptedData);

                encryptedKey.ReferenceList.Add(new DataReference(encryptedData.Id));
            }

            var securityXml = GetSecurity() ?? CreateSecurity();

            foreach (var encryptedData in encryptedDataList)
            {
                Insert(encryptedData.GetXml(), securityXml);
            }

            Insert(encryptedKey.GetXml(), securityXml);
        }
        public void DecryptEncryptedKey_KeyInfoEncryptedKey()
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            string xml = "<root>  <child>sample</child>   </root>";

            doc.LoadXml(xml);

            var random  = new SecureRandom();
            var keydata = new byte[256 / 8];

            random.NextBytes(keydata);
            var param = new KeyParameter(keydata);

            keydata = new byte[128 / 8];
            random.NextBytes(keydata);
            var innerParam = new KeyParameter(keydata);

            keydata = new byte[192 / 8];
            random.NextBytes(keydata);
            var outerParam = new KeyParameter(keydata);

            EncryptedXml exml = new EncryptedXml(doc);

            exml.AddKeyNameMapping("aes", param);

            EncryptedKey ekey = new EncryptedKey();

            byte[] encKeyBytes = EncryptedXml.EncryptKey(outerParam.GetKey(), param);
            ekey.CipherData       = new CipherData(encKeyBytes);
            ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
            ekey.Id      = "Key_ID";
            ekey.KeyInfo = new KeyInfo();
            ekey.KeyInfo.AddClause(new KeyInfoName("aes"));

            KeyInfo topLevelKeyInfo = new KeyInfo();

            topLevelKeyInfo.AddClause(new KeyInfoEncryptedKey(ekey));

            EncryptedKey ekeyTopLevel = new EncryptedKey();

            byte[] encTopKeyBytes = EncryptedXml.EncryptKey(innerParam.GetKey(), outerParam);
            ekeyTopLevel.CipherData       = new CipherData(encTopKeyBytes);
            ekeyTopLevel.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
            ekeyTopLevel.KeyInfo          = topLevelKeyInfo;

            doc.LoadXml(ekeyTopLevel.GetXml().OuterXml);

            byte[] decryptedKey = exml.DecryptEncryptedKey(ekeyTopLevel);
            Assert.Equal(innerParam.GetKey(), decryptedKey);

            EncryptedData eData = new EncryptedData();

            eData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
            eData.KeyInfo          = topLevelKeyInfo;
            var decryptedAlg = exml.GetDecryptionKey(eData, null);

            Assert.Equal(outerParam.GetKey(), ((KeyParameter)decryptedAlg).GetKey());
        }
Exemple #7
0
        private static string GetMgfAlgorithm(EncryptedKey encryptedKey)
        {
            string xpath = ".//*[local-name()='EncryptionMethod']/*[local-name()='MGF']";

            var node = encryptedKey.GetXml().SelectSingleNode(xpath) as XmlElement;

            return(node?.GetAttribute("Algorithm"));
        }
        public void DecryptEncryptedKey_KeyInfoRetrievalMethod()
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            string xml = "<root>  <child>sample</child>   </root>";

            doc.LoadXml(xml);

            var random  = new SecureRandom();
            var ivdata  = new byte[128 / 8];
            var keydata = new byte[256 / 8];

            random.NextBytes(ivdata);
            random.NextBytes(keydata);
            var param = new ParametersWithIV(new KeyParameter(keydata), ivdata);

            keydata = new byte[128 / 8];
            random.NextBytes(ivdata);
            random.NextBytes(keydata);
            var innerParam = new ParametersWithIV(new KeyParameter(keydata), ivdata);

            XmlDecryption exml = new XmlDecryption(doc);

            exml.AddKeyNameMapping("aes", param);

            EncryptedKey ekey = new EncryptedKey();

            byte[] encKeyBytes = XmlEncryption.EncryptKey(((KeyParameter)innerParam.Parameters).GetKey(), (KeyParameter)param.Parameters);
            ekey.CipherData       = new CipherData(encKeyBytes);
            ekey.EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url);
            ekey.Id      = "Key_ID";
            ekey.KeyInfo = new KeyInfo();
            ekey.KeyInfo.AddClause(new KeyInfoName("aes"));

            doc.LoadXml(ekey.GetXml().OuterXml);

            EncryptedKey ekeyRetrieval    = new EncryptedKey();
            KeyInfo      keyInfoRetrieval = new KeyInfo();

            keyInfoRetrieval.AddClause(new KeyInfoRetrievalMethod("#Key_ID"));
            ekeyRetrieval.KeyInfo = keyInfoRetrieval;

            byte[] decryptedKey = exml.DecryptEncryptedKey(ekeyRetrieval);
            Assert.Equal(((KeyParameter)innerParam.Parameters).GetKey(), decryptedKey);

            EncryptedData eData = new EncryptedData();

            eData.EncryptionMethod = new EncryptionMethod(NS.XmlEncAES256Url);
            eData.KeyInfo          = keyInfoRetrieval;
            var decryptedAlg = exml.GetDecryptionKey(eData, NS.None);

            Assert.Equal(((KeyParameter)innerParam.Parameters).GetKey(), ((KeyParameter)decryptedAlg).GetKey());
        }
        public void DecryptEncryptedKey_KeyInfoEncryptedKey()
        {
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            string xml = "<root>  <child>sample</child>   </root>";

            doc.LoadXml(xml);

            using (Aes aes = Aes.Create())
                using (Aes outerAes = Aes.Create())
                    using (Aes innerAes = Aes.Create())
                    {
                        outerAes.KeySize = 192;
                        innerAes.KeySize = 128;

                        EncryptedXml exml = new EncryptedXml(doc);
                        exml.AddKeyNameMapping("aes", aes);

                        EncryptedKey ekey        = new EncryptedKey();
                        byte[]       encKeyBytes = EncryptedXml.EncryptKey(outerAes.Key, aes);
                        ekey.CipherData       = new CipherData(encKeyBytes);
                        ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
                        ekey.Id      = "Key_ID";
                        ekey.KeyInfo = new KeyInfo();
                        ekey.KeyInfo.AddClause(new KeyInfoName("aes"));

                        KeyInfo topLevelKeyInfo = new KeyInfo();
                        topLevelKeyInfo.AddClause(new KeyInfoEncryptedKey(ekey));

                        EncryptedKey ekeyTopLevel   = new EncryptedKey();
                        byte[]       encTopKeyBytes = EncryptedXml.EncryptKey(innerAes.Key, outerAes);
                        ekeyTopLevel.CipherData       = new CipherData(encTopKeyBytes);
                        ekeyTopLevel.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
                        ekeyTopLevel.KeyInfo          = topLevelKeyInfo;

                        doc.LoadXml(ekeyTopLevel.GetXml().OuterXml);

                        byte[] decryptedKey = exml.DecryptEncryptedKey(ekeyTopLevel);
                        Assert.Equal(innerAes.Key, decryptedKey);

                        EncryptedData eData = new EncryptedData();
                        eData.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
                        eData.KeyInfo          = topLevelKeyInfo;
                        SymmetricAlgorithm decryptedAlg = exml.GetDecryptionKey(eData, null);
                        Assert.Equal(outerAes.Key, decryptedAlg.Key);
                    }
        }
        public void GetDecryptionKey_CarriedKeyName()
        {
            var random  = new SecureRandom();
            var ivdata  = new byte[128 / 8];
            var keydata = new byte[256 / 8];

            random.NextBytes(ivdata);
            random.NextBytes(keydata);
            var param = new ParametersWithIV(new KeyParameter(keydata), ivdata);

            keydata = new byte[128 / 8];
            random.NextBytes(ivdata);
            random.NextBytes(keydata);
            var innerParam = new ParametersWithIV(new KeyParameter(keydata), ivdata);

            EncryptedData edata = new EncryptedData();

            edata.KeyInfo = new KeyInfo();
            edata.KeyInfo.AddClause(new KeyInfoName("aes"));

            EncryptedKey ekey = new EncryptedKey();

            byte[] encKeyBytes = EncryptedXml.EncryptKey(((KeyParameter)innerParam.Parameters).GetKey(), (KeyParameter)param.Parameters);
            ekey.CipherData       = new CipherData(encKeyBytes);
            ekey.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
            ekey.CarriedKeyName   = "aes";
            ekey.KeyInfo          = new KeyInfo();
            ekey.KeyInfo.AddClause(new KeyInfoName("another_aes"));

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(ekey.GetXml().OuterXml);

            EncryptedXml exml = new EncryptedXml(doc);

            exml.AddKeyNameMapping("another_aes", param);
            var decryptedAlg = exml.GetDecryptionKey(edata, EncryptedXml.XmlEncAES256Url);

            Assert.IsType <KeyParameter>(decryptedAlg);
            Assert.Equal(((KeyParameter)innerParam.Parameters).GetKey(), ((KeyParameter)decryptedAlg).GetKey());
        }
Exemple #11
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);
        }
        /// <summary>
        /// Encrypts a list of elements.
        /// </summary>
        /// <param name="elementToAddEncKeysTo"></param>
        /// <param name="elementsToEncrypt"></param>
        /// <param name="certificates"></param>
        /// <param name="cipherKey"></param>
        public void Encrypt(XmlElement elementToAddEncKeysTo,
                            IList <XmlElement> elementsToEncrypt,
                            X509Certificate2Collection certificates, byte[] cipherKey)
        {
            ArgumentUtils.CheckNotNull(elementToAddEncKeysTo, "elementToAddEncKeysTo");
            ArgumentUtils.CheckNotNullNorEmpty(elementsToEncrypt, "elementsToEncrypt");
            CertificateUtils.CheckNotNullOrEmpty(certificates, "certificates");

            // Check all the elements to encrypt are not the same as the element
            // to add the keys to and check they belong to the same document.
            foreach (XmlElement elementToEncrypt in elementsToEncrypt)
            {
                if (elementToEncrypt == elementToAddEncKeysTo)
                {
                    throw new XspException(
                              "Cannot add keys to an element that is being encrypted");
                }

                if (elementToAddEncKeysTo.OwnerDocument !=
                    elementToEncrypt.OwnerDocument)
                {
                    throw new XspException(
                              "Elements to encrypt must belong to the same document as the " +
                              "keys element");
                }

                if (XmlUtils.IsDescendant(elementToEncrypt, elementToAddEncKeysTo))
                {
                    throw new XspException(
                              "Element the keys are added to cannot be a child element of an " +
                              "element to encrypt");
                }
            }

            // Get the container document
            XmlDocument containerDoc = elementToAddEncKeysTo.OwnerDocument;

            // Create a random session key
            RijndaelManaged sessionKey = new RijndaelManaged();

            sessionKey.KeySize = 256;

            if (cipherKey != null)
            {
                sessionKey.Key = cipherKey;
            }

            IList <string> referenceIdList = new List <string>();

            foreach (XmlElement elementToEncrypt in elementsToEncrypt)
            {
                // Generate a unique reference identifier
                string referenceId = "_" + Guid.NewGuid().ToString();

                // Add it to the reference list
                referenceIdList.Add(referenceId);

                // Create the encrypted data
                EncryptedData encryptedData = XmlSecurityUtils.Encrypt(
                    sessionKey, elementToEncrypt, referenceId);

                // Replace the original element with the encrypted data
                EncryptedXml.ReplaceElement(elementToEncrypt, encryptedData, false);
            }

            foreach (X509Certificate2 certificate in certificates)
            {
                // Create the encrypted key
                EncryptedKey encryptedKey = XmlSecurityUtils.CreateEncryptedKey(
                    sessionKey, certificate, referenceIdList);

                // Import the encrypted key element into the container document
                XmlNode encryptedKeyElem =
                    containerDoc.ImportNode(encryptedKey.GetXml(), true);

                elementToAddEncKeysTo.AppendChild(encryptedKeyElem);
            }
        }