.Net Core警告未配置XML加密器

Igo*_*ova 10 c# .net-core .net-core-2.2

当我启动服务(Docker容器中的.Net Core 2.2上的API)时,我得到了一个警告:

未配置XML加密器。密钥{daa53741-8295-4c9b-ae9c-e69b003f16fa}可以以未加密形式持久存储。

我没有配置DataProtection。我找到了配置DataProtection的解决方案,但不需要保存此密钥。对我来说,如果密钥只保留到应用程序重新启动,就可以了-没关系。但我不需要在日志中看到此警告

有任何想法吗?我们该怎么做?

我的启动类如下所示:

public class Startup {
  public Startup(IConfiguration configuration) {
    Configuration = configuration;
  }

  public IConfiguration Configuration { get; }

  public void ConfigureServices(IServiceCollection services) {
    services.AddMemoryCache();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version"));
  }

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime) {
    if (env.IsDevelopment()) {
      app.UseDeveloperExceptionPage();
    }

    app.UseMvc();

    lifetime.ApplicationStarted.Register(OnApplicationStarted);
    lifetime.ApplicationStopping.Register(OnShutdown);
  }

  public void OnApplicationStarted() {
    Console.Out.WriteLine($"Open Api Started");
  }

  public void OnShutdown() {
    Console.Out.WriteLine($"Open Api is shutting down.");
  }
}
Run Code Online (Sandbox Code Playgroud)

也许对我的项目包也有帮助

<ItemGroup>
    <PackageReference Include="BouncyCastle.NetCore" Version="1.8.5" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="3.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.5.4" />
    <PackageReference Include="Oracle.ManagedDataAccess.Core" Version="2.18.6" />
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)

Mik*_*laj 16

您可以在 中通过以下方式显式配置您的加密算法.NET 6

using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;

...

var builder = WebApplication.CreateBuilder(args);

...

builder.Services.AddDataProtection().UseCryptographicAlgorithms(
    new AuthenticatedEncryptorConfiguration
    {
        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
        ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
    });
Run Code Online (Sandbox Code Playgroud)

配置 ASP.NET Core 数据保护

默认加密算法为 AES-256-CBC,默认验证算法为 HMACSHA256。默认策略可以由系统管理员通过计算机范围的策略来设置,但是对 UseCryptographicAlgorithms 的显式调用会覆盖默认策略。

调用 UseCryptographicAlgorithms 允许您从预定义的内置列表中指定所需的算法。您无需担心算法的实现。在上述场景中,如果在 Windows 上运行,数据保护系统会尝试使用 AES 的 CNG 实现。否则,它将回退到托管 System.Security.Cryptography.Aes 类。

您可以通过调用 UseCustomCryptographicAlgorithms 手动指定实现。

该解决方案也将解决基于 docker 的 Linux 机器上的警告。

  • 我已经尝试过了,但仍然遇到同样的错误。 (9认同)

Ham*_*RIM 5

这可能是一个权限错误,但你必须确定它。抛出此错误时尝试登录。我看到在开发环境中出现此错误的原因很多,通常是文件读取权限或找不到文件或没有文件。

用下面的日志算法包装你的主函数,看看有什么问题:

public static void Main(string[] args)
{
    CurrentDirectoryHelpers.SetCurrentDirectory();

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Information()
        .MinimumLevel.Override("Serilog", LogEventLevel.Information)
        .WriteTo.File("Logs/LogFrom_ProgramMain.txt")
        .CreateLogger();

    try
    {
        var whb = WebHost.CreateDefaultBuilder(args).UseContentRoot(Directory.GetCurrentDirectory());
        //whb... your codes    
        Log.Logger.Information("Information:blabla");
    }
    catch(Exception ex)
    {
        Log.Logger.Error("Main handled an exception: " + ex.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

不要轻信代码,看看。

如果需要,您可以使用此辅助方法:

internal class CurrentDirectoryHelpers
{
    internal const string AspNetCoreModuleDll = "aspnetcorev2_inprocess.dll";

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

    [System.Runtime.InteropServices.DllImport(AspNetCoreModuleDll)]
    private static extern int http_get_application_properties(ref IISConfigurationData iiConfigData);

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    private struct IISConfigurationData
    {
        public IntPtr pNativeApplication;
        [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]
        public string pwzFullApplicationPath;
        [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]
        public string pwzVirtualApplicationPath;
        public bool fWindowsAuthEnabled;
        public bool fBasicAuthEnabled;
        public bool fAnonymousAuthEnable;
    }

    public static void SetCurrentDirectory()
    {
        try
        {
            // Check if physical path was provided by ANCM
            var sitePhysicalPath = Environment.GetEnvironmentVariable("ASPNETCORE_IIS_PHYSICAL_PATH");
            if (string.IsNullOrEmpty(sitePhysicalPath))
            {
                // Skip if not running ANCM InProcess
                if (GetModuleHandle(AspNetCoreModuleDll) == IntPtr.Zero)
                {
                    return;
                }
                IISConfigurationData configurationData = default(IISConfigurationData);
                if (http_get_application_properties(ref configurationData) != 0)
                {
                    return;
                }
                sitePhysicalPath = configurationData.pwzFullApplicationPath;
            }

            Environment.CurrentDirectory = sitePhysicalPath;
        }
        catch
        {
            // ignore
        }
    }
}
Run Code Online (Sandbox Code Playgroud)