在 .Net Core 3.1 中解密 app.config 连接字符串

Posted

技术标签:

【中文标题】在 .Net Core 3.1 中解密 app.config 连接字符串【英文标题】:Decrypting app.config connection strings in .Net Core 3.1 【发布时间】:2022-02-19 09:38:12 【问题描述】:

我有以下控制台应用程序代码:

// Get the app config file.
var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// Get the sections to unprotect.
ConfigurationSection connStrings = configuration.ConnectionStrings;

string connection = null;

if (connStrings != null)

    // UNPROTECT
    connStrings.SectionInformation.UnprotectSection();

    connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;

此代码在 Framework 4.8 上运行良好,但当我在 Core 3.1 上尝试时,它会抛出

PlatformNotSupportedException

在“UNPROTECT”代码处。

这是在同一个工作站上。

ConfigurationManager 和 SectionInformation 的官方文档都显示了与 Core 3.0 和 3.1 的兼容性。

我猜这些类与Core“兼容”是为了方便访问配置文件,但解密不是因为解密的密钥存储在Framework中,而是Core是跨平台的,因此不会有访问密钥。 (是吗?)

如果此平台不支持连接字符串的解密,是否有其他加密/解密连接字符串的首选替代方法?

我高高在上,但似乎找不到任何东西。

注意:解密加密连接字符串的能力是必不可少的!

【问题讨论】:

UnprotectSection MS Docs 不显示与 .NET Core 的兼容性,仅显示与 .NET Framework 和 .NET 平台扩展 (docs.microsoft.com/en-us/dotnet/api/…) 的兼容性。我认为您需要查看 Windows 兼容包 (docs.microsoft.com/en-us/dotnet/core/porting/…) 才能安装这些平台扩展。有关 Windows 包的更多信息:***.com/questions/53097067/… 【参考方案1】:

ConfigurationManager 类在 DotNetCore 中已被弃用,它已被替换为 IConfiguration 类,您可以使用 ConfigurationBuilder 类构建它,这是加载 json 文件的示例(只是需要注意两个 nuget 依赖项分别是 Microsoft.Extensions.ConfigurationMicrosoft.Extensions.Configuration.Json):


var config = new ConfigurationBuilder()
    .AddJsonFile("Config.json", true) // bool to say whether it is optional
    .Build()

如前所述,这将为您提供 IConfiguration 类的实例,该类已记录在 here 中,但与 ConfigurationManager 非常相似

config.json 的示例:


  "ConnectionStrings": 
    "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
  ,

【讨论】:

它会处理值的加密/解密吗?我在那个班级中没有看到任何似乎表明这一点的东西。 @aaron 看看这个docs.microsoft.com/en-us/aspnet/core/security/…

以上是关于在 .Net Core 3.1 中解密 app.config 连接字符串的主要内容,如果未能解决你的问题,请参考以下文章

抛出异常:'System.PlatformNotSupportedException'。如何在 dotnet core 3.1 中加密和解密安全字符串?

无法在 .Net Core 中使用 RSA 私钥解密连接字符串

Wcf 服务在 .NET Core 3.1 控制台应用程序中工作,但在 ASP.NET Core 3.1 Web API 中无法工作

将项目从 2.2 更新到 3.1(缺少程序集)或如何在 .NET Core 中使用 API POST 请求时,PostAsJsonAsync()在 .Net Core 3.1 中不起作用 [重复]

无法在 .net core 3.1 中注入依赖项

.NET Core加解密实战系列之——RSA非对称加密算法