コード例 #1
0
        /// <summary>
        /// Encrypt data with X509 certificate
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public override System.Xml.XmlNode Encrypt(System.Xml.XmlNode node)
        {
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.LoadXml(node.OuterXml);

            EncryptedXml eXml = new EncryptedXml();
            EncryptedData eData = eXml.Encrypt(doc.DocumentElement, cert);
            return eData.GetXml();
        }
コード例 #2
0
        public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, AsymmetricAlgorithm publicKey)
        {
            XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;

            EncryptedXml eXml = new EncryptedXml();
            eXml.AddKeyNameMapping("encKey", publicKey);

            EncryptedData edElement = eXml.Encrypt(elementToEncrypt, "encKey");
            EncryptedXml.ReplaceElement(elementToEncrypt, edElement, false);
        }
コード例 #3
0
 /// <summary>
 /// 加密Xml。
 /// </summary>
 /// <param name="doc"></param>
 public static void EncryptorXml(XmlDocument doc)
 {
     if (doc != null)
     {
         XmlElement encElement = doc.DocumentElement;
         EncryptedXml encXml = new EncryptedXml(doc);
         encXml.AddKeyNameMapping("session", keyAlgorithm);
         EncryptedData encData = encXml.Encrypt(encElement, "session");
         EncryptedXml.ReplaceElement(encElement, encData, false);
     }
 }
コード例 #4
0
        public void LoadKeyValuePairsFromValidEncryptedXml()
        {
            var xml = @"
                <settings>
                    <Data.Setting>
                        <DefaultConnection>
                            <Connection.String>Test.Connection.String</Connection.String>
                            <Provider>SqlClient</Provider>
                        </DefaultConnection>
                        <Inventory>
                            <ConnectionString>AnotherTestConnectionString</ConnectionString>
                            <Provider>MySql</Provider>
                        </Inventory>
                    </Data.Setting>
                </settings>";

            // This AES key will be used to encrypt the 'Inventory' element
            var aes = Aes.Create();
            aes.KeySize = 128;
            aes.GenerateKey();

            // Perform the encryption
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);
            var encryptedXml = new EncryptedXml(xmlDocument);
            encryptedXml.AddKeyNameMapping("myKey", aes);
            var elementToEncrypt = (XmlElement)xmlDocument.SelectSingleNode("//Inventory");
            EncryptedXml.ReplaceElement(elementToEncrypt, encryptedXml.Encrypt(elementToEncrypt, "myKey"), content: false);

            // Quick sanity check: the document should no longer contain an 'Inventory' element
            Assert.Null(xmlDocument.SelectSingleNode("//Inventory"));

            // Arrange
            var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath, new EncryptedXmlDocumentDecryptor(doc =>
            {
                var innerEncryptedXml = new EncryptedXml(doc);
                innerEncryptedXml.AddKeyNameMapping("myKey", aes);
                return innerEncryptedXml;
            }));

            // Act
            xmlConfigSrc.Load(StringToStream(xmlDocument.OuterXml));

            // Assert
            Assert.Equal("Test.Connection.String", xmlConfigSrc.Get("DATA.SETTING:DEFAULTCONNECTION:CONNECTION.STRING"));
            Assert.Equal("SqlClient", xmlConfigSrc.Get("DATA.SETTING:DefaultConnection:Provider"));
            Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("data.setting:inventory:connectionstring"));
            Assert.Equal("MySql", xmlConfigSrc.Get("Data.setting:Inventory:Provider"));
        }
コード例 #5
0
		public override XmlNode Encrypt (XmlNode node)
		{
			XmlDocument doc = new ConfigurationXmlDocument ();
			
			doc.Load (new StringReader (node.OuterXml));

			EncryptedXml ex = new EncryptedXml (doc);

			ex.AddKeyNameMapping ("Rsa Key", GetProvider ());

			EncryptedData d = ex.Encrypt (doc.DocumentElement, "Rsa Key");

			return d.GetXml();
		}
コード例 #6
0
        EncryptedData IInternalCertificateXmlEncryptor.PerformEncryption(EncryptedXml encryptedXml, XmlElement elementToEncrypt)
        {
            var cert = _certFactory()
                ?? CryptoUtil.Fail<X509Certificate2>("Cert factory returned null.");

            if (_logger.IsVerboseLevelEnabled())
            {
                _logger.LogVerboseF($"Encrypting to X.509 certificate with thumbprint '{cert.Thumbprint}'.");
            }

            try
            {
                return encryptedXml.Encrypt(elementToEncrypt, cert);
            }
            catch (Exception ex)
            {
                if (_logger.IsErrorLevelEnabled())
                {
                    _logger.LogErrorF(ex, $"An error occurred while encrypting to X.509 certificate with thumbprint '{cert.Thumbprint}'.");
                }
                throw;
            }
        }
コード例 #7
0
ファイル: SAML20Assertion.cs プロジェクト: HRINY/HRI-Umbraco
        /// <summary>
        /// Accepts SAML Response, serializes it to XML and signs using the supplied certificate
        /// </summary>
        /// <param name="Response">SAML 2.0 Response</param>
        /// <param name="SigningCert">X509 certificate</param>
        /// <returns>XML Document with computed signature</returns>
        private static XmlDocument SerializeAndSignSAMLResponse(ResponseType Response, string partnerSP)
        {
            // Set serializer and writers for action
            XmlSerializer responseSerializer = new XmlSerializer(Response.GetType());
            StringWriter stringWriter = new StringWriter();
            XmlWriter responseWriter = XmlTextWriter.Create(stringWriter, new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true, Encoding = Encoding.UTF8 });
            responseSerializer.Serialize(responseWriter, Response);
            responseWriter.Close();
            XmlDocument xmlResponse = new XmlDocument();
            xmlResponse.LoadXml(stringWriter.ToString());
            XmlElement elementToEncrypt = xmlResponse.GetElementsByTagName("saml:Assertion")[0] as XmlElement;

            //////////////////////////////////////////////////
            // Create a new instance of the EncryptedXml class
            // and use it to encrypt the XmlElement with the
            // X.509 Certificate.
            //////////////////////////////////////////////////

            EncryptedXml eXml = new EncryptedXml();

            // Encrypt the element.
            var certificate = SAMLConfiguration.Current.CertificateManager.GetPartnerCertificate(partnerSP);
            EncryptedData edElement = eXml.Encrypt(elementToEncrypt, certificate);

            XmlElement encryptedAssertion = xmlResponse.CreateElement("saml2", "EncryptedAssertion", "urn:oasis:names:tc:SAML:2.0:assertion");
            EncryptedXml.ReplaceElement(encryptedAssertion, edElement, true);

            ////////////////////////////////////////////////////
            // Replace the element from the original XmlDocument
            // object with the EncryptedData element.
            ////////////////////////////////////////////////////
            xmlResponse.GetElementsByTagName("Response")[0].ReplaceChild(encryptedAssertion, elementToEncrypt);

            //Get the X509 info
            XmlElement issuerSerialElement = xmlResponse.CreateElement("ds", "X509IssuerSerial", SignedXml.XmlDsigNamespaceUrl);
            XmlElement issuerNameElement = xmlResponse.CreateElement("ds", "X509IssuerName", SignedXml.XmlDsigNamespaceUrl);
            issuerNameElement.AppendChild(xmlResponse.CreateTextNode(certificate.IssuerName.Name));
            issuerSerialElement.AppendChild(issuerNameElement);
            XmlElement serialNumberElement = xmlResponse.CreateElement("ds", "X509SerialNumber", SignedXml.XmlDsigNamespaceUrl);
            serialNumberElement.AppendChild(xmlResponse.CreateTextNode(certificate.SerialNumber));
            issuerSerialElement.AppendChild(serialNumberElement);

            // Set requested namespaces
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["EncryptedData"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["EncryptionMethod"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["KeyInfo"].Prefix = "ds";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["EncryptedKey"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["EncryptionMethod"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["CipherData"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["xenc:CipherData"]["CipherValue"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["KeyInfo"].Prefix = "ds";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["ds:KeyInfo"]["X509Data"].Prefix = "ds";
            // We don't need this for MagnaCare
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["ds:KeyInfo"]["ds:X509Data"].RemoveChild(xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["ds:KeyInfo"]["ds:X509Data"]["X509Certificate"]);
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["CipherData"].Prefix = "xenc";
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["xenc:CipherData"]["CipherValue"].Prefix = "xenc";

            //Add X509 Issuer Info
            xmlResponse.DocumentElement["saml2:EncryptedAssertion"]["xenc:EncryptedData"]["ds:KeyInfo"]["xenc:EncryptedKey"]["ds:KeyInfo"]["ds:X509Data"].AppendChild(issuerSerialElement);

            // Set the namespace for prettire and more consistent XML
            var ns = new XmlNamespaceManager(xmlResponse.NameTable);
            ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            ns.AddNamespace("xenc", "http://www.w3.org/2001/04/xmlenc#");

            CertificateUtility.AppendSignatureToXMLDocument(ref xmlResponse, "#" + ((AssertionType)Response.Items[0]).ID);

            return xmlResponse;
        }
コード例 #8
0
        public static void EncryptXmlDocument(Stream sourceXmlFile,
            Stream destinationXmlFile,
            String xpathNodeToEncrypt,
            Dictionary<String, String> namespaces,
            X509Certificate2 certificate)
        {
            // Carico il documento XML
            XmlDocument doc = new XmlDocument();
            doc.Load(sourceXmlFile);

            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
            if (namespaces != null)
            {
                foreach (var prefix in namespaces.Keys)
                {
                    namespaceManager.AddNamespace(prefix, namespaces[prefix]);
                }
            }

            // Estraggo l'elemento da cifrare
            XmlElement elementToEncrypt = doc.SelectSingleNode(xpathNodeToEncrypt, namespaceManager) as XmlElement;

            // Cifro il nodo di tipo elemento
            EncryptedXml enc = new EncryptedXml(doc);
            EncryptedData ed = enc.Encrypt(elementToEncrypt, certificate);

            // Lo sostituisco all'elemento originale
            EncryptedXml.ReplaceElement(elementToEncrypt,
                ed, false);

            // Salvo il risultato
            doc.Save(destinationXmlFile);
        }
コード例 #9
0
        public ActionResult Index(XmlModel model)
        {
            if (model.Action == "encrypt")
            {
                var recipientCertificate = LoadCertificate(model.RecipientThumbprint);
                var signingCertificate = LoadCertificate(model.SenderThumbprint);
                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(model.PlainText);

                var elementToEncrypt = xmlDocument.GetElementsByTagName("message")[0] as XmlElement;
                var encryptedXml = new EncryptedXml();

                // Encrypt the element.
                var encryptedElement = encryptedXml.Encrypt(elementToEncrypt, recipientCertificate);
                EncryptedXml.ReplaceElement(elementToEncrypt, encryptedElement, false);

                // Sign the document
                var signedXml = new SignedXml(xmlDocument) { SigningKey = signingCertificate.PrivateKey };
                var reference = new Reference { Uri = string.Empty };

                var transform = new XmlDsigC14NTransform();
                reference.AddTransform(transform);

                var envelope = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(envelope);
                signedXml.AddReference(reference);

                var keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(signingCertificate));
                signedXml.KeyInfo = keyInfo;
                signedXml.ComputeSignature();

                var xmlDigitalSignature = signedXml.GetXml();
                xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(xmlDigitalSignature, true));

                model.PlainText = "";
                model.Envelope = XmlToString(xmlDocument);
            }
            else if (model.Action == "decrypt")
            {
                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(model.Envelope);

                // Validate the signature
                var signedXml = new SignedXml(xmlDocument);
                var nodeList = xmlDocument.GetElementsByTagName("Signature");

                if (nodeList.Count <= 0)
                {
                    throw new Exception("No signature found.");
                }

                signedXml.LoadXml((XmlElement)nodeList[0]);
                AsymmetricAlgorithm signingKey;

                if (!signedXml.CheckSignatureReturningKey(out signingKey))
                {
                    throw new Exception("Invalid Signature");
                }
                else
                {
                    IEnumerable<X509Certificate2> keyInfoCertificates =
                        signedXml.KeyInfo.OfType<KeyInfoX509Data>()
                            .SelectMany(x => x.Certificates.Cast<X509Certificate2>());
                    var signingCertificate = keyInfoCertificates.FirstOrDefault(x => x.PublicKey.Key == signingKey);
                    if (signingCertificate == null)
                    {
                        throw new Exception("Signing certificate not found in KeyInfo.");
                    }
                    model.SenderSubject = signingCertificate.Subject;
                }

                var encryptedXml = new EncryptedXml(xmlDocument);
                encryptedXml.DecryptDocument();

                model.Envelope = "";
                model.PlainText = XmlToString(xmlDocument);
            }

            ModelState.Clear();
            model.RecipientThumbprint = RecipientThumbprint;
            model.SenderThumbprint = SenderThumbprint;
            return View(model);
        }
コード例 #10
0
        EncryptedData IInternalCertificateXmlEncryptor.PerformEncryption(EncryptedXml encryptedXml, XmlElement elementToEncrypt)
        {
            var cert = _certFactory()
                ?? CryptoUtil.Fail<X509Certificate2>("Cert factory returned null.");

            _logger?.EncryptingToX509CertificateWithThumbprint(cert.Thumbprint);

            try
            {
                return encryptedXml.Encrypt(elementToEncrypt, cert);
            }
            catch (Exception ex)
            {
                _logger?.AnErrorOccurredWhileEncryptingToX509CertificateWithThumbprint(cert.Thumbprint, ex);
                throw;
            }
        }
コード例 #11
0
ファイル: BLITEMMOVE.cs プロジェクト: rehman922/VIRETAIL
 public XmlDocument CreateEncriptedXmlfile(string txtXml)
 {
     XmlDocument xmlDoc = new XmlDocument();
     try
     {
         xmlDoc.LoadXml(txtXml);
         var rsa = new RSACryptoServiceProvider();
         XmlElement xmlElemt;
         xmlElemt = xmlDoc.DocumentElement;
         EncryptedXml xmlEnc = new EncryptedXml(xmlDoc);
         xmlEnc.AddKeyNameMapping("asyncKey", rsa);
         EncryptedData encXml = xmlEnc.Encrypt(xmlElemt, "asyncKey");
         EncryptedXml.ReplaceElement(xmlElemt, encXml, false);
     }
     catch (XmlException ex)
     {
         throw ex;
     }
     return  xmlDoc ;
 }
コード例 #12
0
        private XmlElement EncryptElement(XmlElement element)
        {
            var encryptedXml = new EncryptedXml();
            var encryptedData = encryptedXml.Encrypt(element, publicFtgpCertificate);

            return encryptedData.GetXml();
        }
コード例 #13
0
        /// <summary>
        /// ����XmlԪ��
        /// </summary>
        /// <param name="doc">XmlDocument</param>
        /// <param name="elmentName">Ҫ���ܵ�Ԫ������</param>
        /// <param name="isContent">����Ԫ������ΪTrue,��������Ԫ��ΪFalse</param>
        public static void EncryptorXmlElement(XmlDocument doc, string elmentName, bool isContent)
        {
            if (doc == null)
                throw new ArgumentNullException("doc");

            EncryptedXml encXml = new EncryptedXml(doc);
            encXml.AddKeyNameMapping("session", keyAlgorithm);

            XmlElement encElement = null;
            EncryptedData encData = null;
            if (string.IsNullOrEmpty(elmentName))
            {
                encElement = doc.DocumentElement;
                encData = encXml.Encrypt(encElement, "session");
                EncryptedXml.ReplaceElement(encElement, encData, isContent);
            }
            else
            {
                XmlNodeList nodeList = doc.GetElementsByTagName(elmentName);
                if (nodeList != null && nodeList.Count > 0)
                {
                    for (int i = 0; i < nodeList.Count; i++)
                    {
                        encElement = nodeList[i] as XmlElement;
                        if (encElement != null)
                        {
                            encData = encXml.Encrypt(encElement, "session");
                            EncryptedXml.ReplaceElement(encElement, encData, isContent);
                        }
                    }
                }
            }
        }