使用RsaProtectedConfigurationProvider加密/解密app.config部分

Jan*_*Jan 6 c# encryption configuration rsa

在我们的程序安装过程中,我们运行此方法来加密app.config的各个部分:

// Get the application configuration file.
Configuration config =
      ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// Define the Rsa provider name.
const string provider = "RsaProtectedConfigurationProvider";

// Get the section to protect.
ConfigurationSection connStrings = config.ConnectionStrings;

if (connStrings != null)
{
    if (!connStrings.SectionInformation.IsProtected)
    {
        if (!connStrings.ElementInformation.IsLocked)
        {
            // Protect the section.
            connStrings.SectionInformation.ProtectSection(provider);

            connStrings.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Full);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止工作正常.但是如果我运行这个程序,我们会遇到几个机器出现以下错误"无法使用提供程序'RsaProtectedConfigurationProvider解密'.来自提供程序的错误消息:无法打开RSA密钥容器 ".

当然,我搜索并找到了这个帮助,但这不起作用.有任何想法吗?

Ali*_*tad 5

是的。

原因是那些工作的机器RsaProtectedConfigurationProvider在他们的machine.config 中进行了设置。那些不工作的,没有它 -只需为这些机器手动添加它

我想这是aspnet_regiis.exe执行的步骤之一。我无法想象你想在所有客户端机器上运行它。

更新

好的,我在您的问题中以粗体显示了错误的主要部分 - 您是对的,这是一个不同的问题。这是一个安全问题。如果您查看位置C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeysC:\ProgramData\Microsoft\Crypto\RSA\MachineKeys取决于操作系统,您会看到许多文件. 您的进程确实有权访问该文件夹,因此只需为应用程序或特定文件的身份授予文件访问整个文件夹的权限(时间戳会告诉您是否已创建它)。


小智 5

我在Win 7上的Visual Studio 2010中进行调试时遇到了类似的问题,UAC设置为默认保护.

为了让我解决这个问题,我必须以管理员身份运行Visual Studio("以管理员身份运行").

尝试运行aspnet_regiis.exe加密我的web.config部分时遇到了同样的问题.如果我没有"以管理员身份"运行命令行/控制台,我会得到一个更加神秘的命令行错误:"对象已经存在."