如何加密 .NET Core 5.0 的 App.config 中的部分或密钥?

问题描述 投票:0回答:1

我制作了一个发送电子邮件的程序,需要将密码存储在 App.config 文件中,但我不希望仅通过打开文件即可访问密码。我想以某种方式加密该密钥所在的部分,或者只是密钥本身,这两种解决方案对我来说都很好。我看过一些关于这个主题的帖子,但没有一个能解决我的问题。我希望获得有关如何执行此操作的详细解释,因为我不是该主题的专家。

我的应用程序配置:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <appSettings>
            <add key="MAIL_USER" value="[email protected]" />
            <add key="MAIL_PASSWORD" value="my_password" />
        </appSettings>
    </configuration>

要检索 SendMail.cs 中的信息,我使用:

string password = ConfigurationManager.AppSettings[("MAIL_PASSWORD")];
c# app-config .net-5
1个回答
0
投票

您可以使用 System.Configuration 命名空间提供的 ProtectedConfiguration 功能。这允许您加密配置文件中的敏感数据。

  1. 加密配置部分:

    打开命令提示符并导航到可执行文件所在的目录。

    运行以下命令来加密

    appSettings
    文件的
    App.config
    部分:

    aspnet_regiis -pef "appSettings" "path\to\your\executable"
    

    此命令使用

    aspnet_regiis
    工具来加密
    appSettings
    部分。将
    "path\to\your\executable"
    替换为可执行文件的实际路径。

  2. 更新您的App.config:

    您的

    App.config
    文件现在应该在
    configProtectionProvider
    部分中有一个额外的
    appSettings
    属性。它可能看起来像这样:

    <appSettings configProtectionProvider="RsaProtectedConfigurationProvider">
      <!-- Encrypted data here -->
    </appSettings>
    
  3. 访问代码中的加密数据:

    在 C# 代码中,您仍然可以使用

    ConfigurationManager.AppSettings

    访问解密的数据

    字符串密码 = ConfigurationManager.AppSettings["MAIL_PASSWORD"];

© www.soinside.com 2019 - 2024. All rights reserved.