解密xml文档时出现问题

2024-03-21

我编写了一些代码来加密包含用户凭据的 XML 配置文件,以及解密该文件的代码。当我在本地计算机上同时运行加密和解密时,它按预期工作。但是,当我部署程序时,仅使用解密代码,xml 文件将无法解密。我收到加密异常:错误数据? 这是我的代码:

    public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, RSA Alg, string Keyname)
    {
        if (Doc == null)
            throw new ArgumentNullException("Doc");
        if (ElementToEncrypt == null)
            throw new ArgumentNullException("Element to Encrypt");
        if (EncryptionElementID == null)
            throw new ArgumentNullException("EncryptionElementID");
        if (Alg == null)
            throw new ArgumentNullException("ALG");
        //specify which xml elements to encrypt
        XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;

        if (elementToEncrypt == null)
            throw new XmlException("The specified element was not found");
        try
        {
            //create session key
            RijndaelManaged sessionkey = new RijndaelManaged();
            sessionkey.KeySize = 256;

            //encrypt using Encrypted exml object and hold in byte array
            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;

            edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
            //encrypt the session key and add it encrypted key 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 data reference to encrypted key

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

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

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



        // 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)
        {
            throw e;
        }
    }


    public static string Decrypt()
    {
            //create XML documentobject and load config file
            XmlDocument xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.Load("config.xml");
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }

            //create container for key
            CspParameters cspParam = new CspParameters();
            cspParam.KeyContainerName = "XML_RSA_FTP_KEY";
            cspParam.Flags = CspProviderFlags.UseMachineKeyStore;
            //create key and store in container
            RSACryptoServiceProvider ftpkey = new RSACryptoServiceProvider(cspParam);


            //add keyname mapping qnd decrypt the document
            EncryptedXml exml = new EncryptedXml(xmlDoc);
            exml.AddKeyNameMapping("ftpkey", ftpkey);
            exml.DecryptDocument();

            //pass decrypted document to extract credentials method
            string details =  Extract_Credentials(xmlDoc);

            //return decrypted log in details
            return details;

    }

任何帮助,将不胜感激。谢谢,达伦


我将您的 Encrypt 函数更改为不传入 RSA Alg,而是使用字符串 Keyname 参数创建 RSACryptoServiceProvider rsaAlg,这应该与 KeyContainerName 的解密中使用的字符串相同,“XML_RSA_FTP_KEY”

当尝试在另一台 PC 上解密时,解密函数抛出“错误数据”异常的原因是 CspParameters 链接到运行加密的 PC 上的会话。

cspParams 对象需要在 XML 中嵌入并加密,以便在另一台 PC 上启用解密。幸运的是,我们可以使用 EncryptionProperty 来实现此目的。

public static void Encrypt(XmlDocument Doc, string ElementToEncrypt, string EncryptionElementID, string Keyname)
    {
        if (Doc == null)
            throw new ArgumentNullException("Doc");
        if (ElementToEncrypt == null)
            throw new ArgumentNullException("Element to Encrypt");
        if (EncryptionElementID == null)
            throw new ArgumentNullException("EncryptionElementID");

        // Create a CspParameters object and specify the name of the key container.
        var cspParams = new CspParameters { KeyContainerName = Keyname }; //"XML_RSA_FTP_KEY"

        // Create a new RSA key and save it in the container.  This key will encrypt 
        // a symmetric key, which will then be encryped in the XML document.
        var rsaAlg = new RSACryptoServiceProvider(cspParams);

        //specify which xml elements to encrypt
        XmlElement elementToEncrypt = Doc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;

        if (elementToEncrypt == null)
            throw new XmlException("The specified element was not found");
        try
        {
            //create session key
            RijndaelManaged sessionkey = new RijndaelManaged();
            sessionkey.KeySize = 256;

            //encrypt using Encrypted exml object and hold in byte array
            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;

            edElement.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncAES256Url);
            //encrypt the session key and add it encrypted key element
            EncryptedKey ek = new EncryptedKey();

            byte[] encryptedKey = EncryptedXml.EncryptKey(sessionkey.Key, rsaAlg, 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 data reference to encrypted key

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

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

            // Save some more information about the key using the EncryptionProperty element.

            // Create a new "EncryptionProperty" XmlElement object. 
            var property = new XmlDocument().CreateElement("EncryptionProperty", EncryptedXml.XmlEncNamespaceUrl);

            // Set the value of the EncryptionProperty" XmlElement object.
            property.InnerText = RijndaelManagedEncryption.EncryptRijndael(Convert.ToBase64String(rsaAlg.ExportCspBlob(true)),
                            "Your Salt string here");

            // Create the EncryptionProperty object using the XmlElement object. 
            var encProperty = new EncryptionProperty(property);

            // Add the EncryptionProperty object to the EncryptedKey object.
            ek.AddProperty(encProperty);

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



            // 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)
        {
            throw;
        }
    }

    public static string Decrypt()
    {
        //create XML documentobject and load config file
        XmlDocument xmlDoc = new XmlDocument();

        try
        {
            xmlDoc.Load("config.xml");
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine(e.Message);
            Console.ReadLine();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.ReadLine();
        }

        //create container for key
        CspParameters cspParam = new CspParameters();
        cspParam.KeyContainerName = "XML_RSA_FTP_KEY";
        cspParam.Flags = CspProviderFlags.UseMachineKeyStore;
        //create key and store in container
        RSACryptoServiceProvider ftpkey = new RSACryptoServiceProvider(cspParam);

        var keyInfo = xmlDoc.GetElementsByTagName("EncryptionProperty")[0].InnerText;
        ftpkey.ImportCspBlob(
            Convert.FromBase64String(RijndaelManagedEncryption.DecryptRijndael(keyInfo,
                "Your Salt string here")));

        //add keyname mapping qnd decrypt the document
        EncryptedXml exml = new EncryptedXml(xmlDoc);
        exml.AddKeyNameMapping("ftpkey", ftpkey);
        exml.DecryptDocument();

        //pass decrypted document to extract credentials method
        string details = Extract_Credentials(xmlDoc);

        //return decrypted log in details
        return details;

    }

看一看here http://www.codeproject.com/Tips/704372/How-to-use-Rijndael-ManagedEncryption-with-Csharp对于 RijndaelManaged 加密类。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

解密xml文档时出现问题 的相关文章

  • 静态只读字符串数组

    我在我的 Web 应用程序中使用静态只读字符串数组 基本上数组有错误代码 我将所有类似的错误代码保存在一个数组中并检查该数组 而不是检查不同常量字符串中的每个错误代码 like public static readonly string m
  • 为什么在连接两个字符串时 Python 比 C 更快?

    目前我想比较 Python 和 C 用来处理字符串的速度 我认为 C 应该比 Python 提供更好的性能 然而 我得到了完全相反的结果 这是 C 程序 include
  • 使用 lambda 表达式注册类型

    我想知道如何在 UnityContainer 中实现这样的功能 container RegisterType
  • 计算 XML 中特定 XML 节点的数量

    请参阅此 XML
  • 使用 C# 登录《我的世界》

    我正在尝试为自己和一些朋友创建一个简单的自定义 Minecraft 启动器 我不需要启动 Minecraft 的代码 只需要登录的实际代码行 例如 据我所知 您过去可以使用 string netResponse httpGET https
  • C++ 是否可以在 MacOS 上与 OpenMP 和 boost 兼容?

    我现在已经尝试了很多事情并得出了一些结论 也许 我监督了一些事情 但似乎我无法完成我想要的事情 问题是 是否有可能使用 OpenMP 和 boost 在 MacOS High Sierra 上编译 C 一些发现 如果我错了请纠正我 Open
  • JNI 将 Char* 2D 数组传递给 JAVA 代码

    我想从 C 代码通过 JNI 层传递以下指针数组 char result MAXTEST MAXRESPONSE 12 12 8 3 29 70 5 2 42 42 在java代码中我写了以下声明 public static native
  • 如何填充 ToolStripComboBox?

    我发现它很难将数据绑定到ToolStripComboBox 好像没有这个ValueMember and DisplayMember特性 怎么绑定呢 访问toolstripcombobox中包装的组合框并访问其ValueMember Disp
  • 为什么在 WebApi 上下文中在 using 块中使用 HttpClient 是错误的?

    那么 问题是为什么在 using 块中使用 HttpClient 是错误的 但在 WebApi 上下文中呢 我一直在读这篇文章不要阻止异步代码 https blog stephencleary com 2012 07 dont block
  • Visual Studio 在构建后显示假错误

    我使用的是 Visual Studio 2017 构建后 sln在调试模式下 我收到错误 但是 当我通过双击错误列表选项卡中的错误来访问错误时 错误会从页面中消失 并且错误数量也会减少 我不太确定这种行为以及为什么会发生这种情况 有超过 2
  • C# 数据表更新多行

    我如何使用数据表进行多次更新 我找到了这个更新 1 行 http support microsoft com kb 307587 my code public void ExportCSV string SQLSyntax string L
  • 类型约束

    我有以下类层次结构 class Header IEnumerable
  • 启动时的 Excel 加载项

    我正在使用 Visual C 创建 Microsoft Excel 的加载项 当我第一次创建解决方案时 它包含一个名为 ThisAddIn Startup 的函数 我在这个函数中添加了以下代码 private void ThisAddIn
  • 打破 ReadFile() 阻塞 - 命名管道 (Windows API)

    为了简化 这是一种命名管道服务器正在等待命名管道客户端写入管道的情况 使用 WriteFile 阻塞的 Windows API 是 ReadFile 服务器已创建启用阻塞的同步管道 无重叠 I O 客户端已连接 现在服务器正在等待一些数据
  • IQueryable 单元或集成测试

    我有一个 Web api 并且公开了一个端点 如下所示 api 假期 name name 这是 Web api 的控制器 get 方法 public IQueryable
  • 为什么这个二维指针表示法有效,而另一个则无效[重复]

    这个问题在这里已经有答案了 这里我编写了一段代码来打印 3x3 矩阵的对角线值之和 这里我必须将矩阵传递给函数 矩阵被传递给指针数组 代码可以工作 但问题是我必须编写参数的方式如下 int mat 3 以下导致程序崩溃 int mat 3
  • 等待 IAsyncResult 函数直至完成

    我需要创建等待 IAsyncResult 方法完成的机制 我怎样才能做到这一点 IAsyncResult result contactGroupServices BeginDeleteContact contactToRemove Uri
  • 这个可变参数模板示例有什么问题?

    基类是 include
  • 使用 C 在 OS X 中获取其他进程的 argv

    我想获得其他进程的argv 例如ps 我使用的是在 Intel 或 PowerPC 上运行的 Mac OS X 10 4 11 首先 我阅读了 ps 和 man kvm 的代码 然后编写了一些 C 代码 include
  • 如何减少具有多个单元的 PdfPTable 的内存消耗

    我正在使用 ITextSharp 创建一个 PDF 它由单个 PdfTable 组成 不幸的是 对于特定的数据集 由于创建了大量 PdfPCell 我遇到了内存不足异常 我已经分析了内存使用情况 我有近百万个单元格的 1 2 在这种情况下有

随机推荐

  • Java 加密替代硬编码密钥

    我是加密新手 我查看了 javax crypto 文档并使用此代码对文件进行了加密 File saveFile new File Settings set saveFile delete FileOutputStream fout new
  • 映射 MMIO 区域写回不起作用

    我希望对 PCIe 设备的所有读写请求都由 CPU 缓存进行缓存 然而 它并没有像我预期的那样工作 这些是我对回写 MMIO 区域的假设 对 PCIe 设备的写入仅在缓存回写时发生 TLP 有效负载的大小是缓存块大小 64B 然而 捕获的
  • p2p0是android中WIFI DIRECT的无线接口吗? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 当我打印 Android 设备中的所有接口时 03 10 19 50 15 484 I System out 22415 lo 03 10
  • PyQt 4 UI 冻结

    下面的程序应该只是累加和 int 并在标签中显示其值 但过了一会儿 GUI 停止工作 而循环继续 from PyQt4 import QtGui QtCore import sys class main window QtGui QWidg
  • JavaScript 中的“可绑定”变量?

    从我对 Flex 的一点经验中 我了解了可绑定变量 例如 文本元素的内容会随着变量的值而变化 我想知道是否可以在 JavaScript 中做这样的事情 例如 假设我有一个 h1 我想包含文档的标题 这可以很容易地完成document get
  • “equal”模板功能是如何实现的? (谓词版本)

    我正在阅读 Accelerated C 一书 其中一个练习要求我们模拟标题中的 equal 函数 到目前为止 我已经实现了简单的版本 它采用三个参数 如下所示 template
  • 禁用适用于平板电脑和 iPad 的 Magento 移动主题

    我制作了一个包含桌面和移动主题的网站 它工作得很好 但在平板电脑和 iPad 中它显示了我不想要的移动主题 所以我使用以下异常 iPhone iPod BlackBerry Pre Palm Googlebot Mobile mobi Sa
  • 不同 django 模型的公共字段集中在一处

    我有一些在多个模型中重复的列 有什么解决方案可以将它们放置在某个地方并使用任何模型吗 您可以通过创建基类并在模型中继承它们来实现这一点 Example class TimestampsModel models Model classmeth
  • Java Swing 在 Eclipse Oxy 4.7.3a 上运行?

    我正在尝试在 macOS high Sierra 上的 eclipseoxygen 4 7 3a 中使用 windowbuilder 它安装得很好 但每次我尝试打开设计部分时 它都会显示此错误 Eclipse 在 0 下运行 但是这个 Ja
  • 在 select2 上设置标签值

    我的页面上有选择字段
  • 从数据库中删除文件和相应条目

    我有一个处理文件管理的网站 用户可以上传文件 添加描述 编辑和删除 这种情况的最佳实践是什么 我将文件存储在文件系统中 我该如何处理文件的删除 在这种情况下 我必须删除实体 数据库中的文件和条目 第一种情况是我删除文件 如果没有错误 我从数
  • 从 Tokio 应用程序使用 Actix:混合 actix_web::main 和 tokio::main?

    目前我主要写的是异步示例Reqwest library https crates io crates reqwest tokio main async fn main gt Result lt Box
  • Caliburn.Micro DisplayRootViewFor 抛出 NullReferenceException

    我的引导程序中有以下代码 private SimpleContainer container protected override void Configure container new SimpleContainer container
  • 从方法返回元组

    我正在编写一个方法 成功时返回一个元组 但是None失败时 我还没有最终确定None 作为失败案例返回 但它是选择之一 我们可以回来吗 1 1对于失败案例 我正在寻找最好的Pythonic方法来实现这一点 以便拆包很容易 请让我知道我们如何
  • 如何添加链接来下载pdf文件nuxt?

    我只想在 nuxt 项目中添加一个下载 pdf 文件的链接 我怎么做 我已经尝试过以下方法 a class btn btn sm btn sub color Download a 它适用于图像 但不适用于 pdf 文件 我发现vue pdf
  • 如何使用 Maven 构建可运行的 JavaFX 应用程序?

    我是 JavaFX 新手 我使用 Maven 创建了一个 Hello World 项目 当我在 Eclipse 中运行它时 它工作得很好 public static void main String args launch args Ove
  • 将类元素更改为界面元素

    当对类图进行建模时 工具箱包含类和接口的特殊对象 它们的不同之处在于它们的图标 这些图标显示在Project Browser如果它们被添加到图表中 它们的属性似乎是相同的 是否可以更改创建为的对象class到一个类型的对象interface
  • 如何在测试已弃用的 Scala 函数时抑制弃用警告?

    假设我有一个库 其中包含已弃用的函数和首选函数 object MyLib def preferredFunction deprecated Use preferredFunction instead 1 0 def deprecatedFu
  • Matlab:如何导出voronoi图中多边形的顶点(坐标)?

    我手头有一个创建的函数文件 它是在图像中画线 img drawline point1 point2 color img 它用于连接图像内的任意两点 我被要求在图像中创建 voronoi 图 不使用绘图功能 目前 我正在尝试显示图像中的线条
  • 解密xml文档时出现问题

    我编写了一些代码来加密包含用户凭据的 XML 配置文件 以及解密该文件的代码 当我在本地计算机上同时运行加密和解密时 它按预期工作 但是 当我部署程序时 仅使用解密代码 xml 文件将无法解密 我收到加密异常 错误数据 这是我的代码 pub