简体   繁体   English

如何在 C# 中使用带有 ProtectSection 方法的 RsaProtectedConfigurationProvider 创建可导出的 RSA 密钥

[英]How can I create an exportable RSA key with RsaProtectedConfigurationProvider with ProtectSection method in C#

In the following example I protect the "DemoWinApp.Properties.Settings" section of the "Sleutels.config" file.在以下示例中,我保护“Sleutels.config”文件的“DemoWinApp.Properties.Settings”部分。

    private static void toggleProtectionSleutelsConfig()
    {
        var fileMap = new ConfigurationFileMap(@"D:\Experimenten\ReadProtectedConfigFile\Sleutels.config");
        var configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
        var sectionGroup = configuration.GetSectionGroup("applicationSettings"); // This is the section group name, change to your needs
        var section = (ClientSettingsSection)sectionGroup.Sections.Get("DemoWinApp.Properties.Settings"); // This is the section name, change to your needs
        var setting = section.Settings.Get("SecretMessage"); // This is the setting name, change to your needs
        Console.WriteLine(setting.Value.ValueXml.InnerText);

        // Toggle beveiliging
        if (!section.SectionInformation.IsProtected)
        {
            //Protecting the specified section with the specified provider
            section.SectionInformation.ProtectSection("RSA");
        }
        else
        {
            section.SectionInformation.UnprotectSection();
        }
        section.SectionInformation.ForceSave = true;
        configuration.Save(ConfigurationSaveMode.Modified);


        Console.ReadKey();
    }

The contents of the "Sleutels.config" file is: “Sleutels.config”文件的内容是:

 <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, &#xD;&#xA; System, Version=2.0.0.0, Culture=neutral, &#xD;&#xA; PublicKeyToken=b77a5c561934e089"> <section name="DemoWinApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <applicationSettings> <DemoWinApp.Properties.Settings> <setting name="SecretMessage" serializeAs="String"> <value>This is the secret message.</value> </setting> </DemoWinApp.Properties.Settings> </applicationSettings> <configProtectedData> <providers> <add name="RSA" type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0,&#xD;&#xA; Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,&#xD;&#xA; processorArchitecture=MSIL" keyContainerName="RobinsKeys" useMachineContainer="true" /> </providers> </configProtectedData> </configuration>

After running the code the "Sleutels.config" file is encrypted and a RSA key container is created in C:\\Documents and Settings\\All Users\\Application Data\\Microsoft\\Crypto\\RSA\\MachineKeys运行代码后,“Sleutels.config”文件被加密,并在C:\\Documents and Settings\\All Users\\Application Data\\Microsoft\\Crypto\\RSA\\MachineKeys创建一个 RSA 密钥容器

If I try to export the RSA key container with the commandline:如果我尝试使用命令行导出 RSA 密钥容器:

c:\windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -pc "RobinsKeys" –exp

Then I get the error message:然后我收到错误消息:

Exporting RSA Keys to file...
Key not valid for use in specified state.

This means that the RSA Key container is not marked as "exportable".这意味着 RSA 密钥容器未标记为“可导出”。 If you would create an key container with the command line, then there is an optional parameter "-exp" to mark the key as exportable.如果您要使用命令行创建密钥容器,则有一个可选参数“-exp”可将密钥标记为可导出。

For example: aspnet_regiis -pc "RobinsKeys" -exp例如:aspnet_regiis -pc "RobinsKeys" -exp

Is this -exp option also available while using the section.SectionInformation.ProtectSection("RSA");使用section.SectionInformation.ProtectSection("RSA");-exp选项是否也可用section.SectionInformation.ProtectSection("RSA"); method in code or as an configuration option in the RSA provider section in the "Sleutels.config" configuration file?代码中的方法还是作为“Sleutels.config”配置文件中RSA提供程序部分中的配置选项?

Any help is appreciated!任何帮助表示赞赏!

To summarize the discussion, you need to create a RSA crypto container programmatically before you can use it to store RSA keys.总结一下讨论,您需要先以编程方式创建RSA 加密容器,然后才能使用它来存储 RSA 密钥。

The reason is that the RSAProtectedConfigurationProvider doesn't have an option to make the automatically created RSA key container exportable.原因是RSAProtectedConfigurationProvider没有使自动创建的 RSA 密钥容器可导出的选项。

As you wrote in the chat, this workaround can be achieved by the following example code (I've added some output to the console, RSA parameters printed are explained here ):正如您在聊天中所写,此解决方法可以通过以下示例代码实现(我已向控制台添加了一些输出, 此处解释打印的 RSA 参数):

void Main()
{
   // Create the CspParameters object and set the key container
   // name used to store the RSA key pair.
   var cp = new System.Security.Cryptography.CspParameters();
   cp.Flags = System.Security.Cryptography.CspProviderFlags.UseMachineKeyStore;
   cp.KeyContainerName = "RobinsKeys";


   // Create a new instance of RSACryptoServiceProvider that accesses
   // the key container MyKeyContainerName.
   // If it is not already there, it will create a new one, which is exportable.
   var myRSA = new System.Security.Cryptography.RSACryptoServiceProvider(cp);
    
   // print it on console
   Console.WriteLine($"=== Container: {cp.KeyContainerName} ===");
   Console.WriteLine(myRSA.ToXmlString(true).Replace("><", ">\n<")); 
}

which can be read in more detail here .可以在这里更详细地阅读。 The link provided also shows how to提供的链接还显示了如何

  • generate and save a key pair生成并保存密钥对
  • get a key from a container从容器中获取密钥
  • delete a key from a container从容器中删除密钥

It might be useful to get a list of containers, this is discussed in a separate question .获取容器列表可能很有用,这将在单独的问题中讨论

Some more information about key containers you can find in this Microsoft article , also about available aspnet_regiis parameters.您可以在这篇 Microsoft 文章中找到有关关键容器的更多信息,以及可用的aspnet_regiis参数。

Once a RSA container is created, it can be used by IIS.一旦创建了 RSA 容器,IIS 就可以使用它。 It is important to understand the difference between user-level and machine-level key containers, which is described in this documentation .了解用户级机器级密钥容器之间的区别很重要,这在本文档中进行了描述


Kindly let me know if anything is missing from the discussion, and I will update this answer.如果讨论中缺少任何内容,请告诉我,我会更新此答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用RsaProtectedConfigurationProvider的ProtectSection Key在哪里? - ProtectSection with RsaProtectedConfigurationProvider where does the Key go? 使用C#/ CSP在HSM中使用不可导出的密钥进行RSA加密 - RSA Encryption with non exportable key in HSM using C# / CSP 如何在C#中唯一识别RSA私钥 - How can I identify RSA Private key uniquely in C# 如何使证书中的私钥不可导出C# - How to make priv key in certificate not exportable C# 如何在c#中使用bouncycastle将pem公钥转换为rsa公钥? - how can i convert pem public key to rsa public key with bouncycastle in c#? c#WebApi如何创建rsa私钥和公钥 - c# WebApi How to create rsa private and public key 如何从 C# 中的私钥字符串创建 RSA 对象? - how to create RSA object from private key string in c#? 如何在C#中加载RSA公钥并将其用于加密某些内容? - How can I load a RSA public key in C# and use it to encrypt something? 如何在C#中使用ANSI X9.31 RSA创建数字签名? - How can I create a digital signature using ANSI X9.31 RSA in C#? C# 生成的 RSA 公钥是一个 XML 文件。 PHP中的公钥如何解密或转换? - The RSA public key generated by C# is an XML file. How can the public key be decrypted or converted in PHP?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM