简体   繁体   English

创建一个 IDataProtectionProvider asp.net core 的实例

[英]Create a instance of IDataProtectionProvider asp.net core

I am trying to create a static class and methods to encrypt and decrypt data in asp.net core.我正在尝试创建一个静态类和方法来加密和解密 asp.net 核心中的数据。

But the problem is that I have to get the "IDataProtectionProvider provider" in constructor with DI and then pass it to the methods so that a CreateProtector be used.但问题是我必须使用 DI 在构造函数中获取“IDataProtectionProvider 提供者”,然后将其传递给方法以便使用 CreateProtector。

I donot want that and directly want to instanciate the IDataProtectionProvider provider in the method it self.我不希望那样,直接想在它自己的方法中实例化 IDataProtectionProvider 提供者。

The controller code:控制器代码:

private readonly IDataProtectionProvider _provider;
public addMDL(IDataProtectionProvider provider)
{
    _provider = provider;
}

public IActionResult OnGet()
{
    DataProProvider.decData(0, "ABC", _provider)
}

and the static class is :静态类是:

public static class DataProProvider
{

    public static string encData(int intData, string strData, IDataProtectionProvider provider)
    {
        string str;
        IDataProtector dataProtector;
        dataProtector = provider.CreateProtector("AA");
        if (!string.IsNullOrEmpty(strData))
        {
            str = dataProtector.Protect(strData);
        }
        else
        {
            str = dataProtector.Protect(intData.ToString());
        }
        return str;
    }

    public static string decData(int intData, string strData, IDataProtectionProvider provider)
    {
        string str;
        IDataProtector dataProtector;
        dataProtector = provider.CreateProtector("A3");
        if (!string.IsNullOrEmpty(strData))
        {
            str = dataProtector.Unprotect(strData);
        }
        else
        {
            str = dataProtector.Unprotect(intData.ToString());
        }
        return str;
    }
}

[UPDATE] [更新]

As per suggestion I have moved to a smpler approch using Encrypting & Decrypting a String in C# enter link description here根据建议,我已使用C# 中的 Encrypting & Decrypting a String移至更简单的方法,请此处输入链接描述

You can refer to a Microsoft recomendation on how to use Data Protection for non-DI solutions ( https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/non-di-scenarios?view=aspnetcore-2.2 ).您可以参考 Microsoft 关于如何将数据保护用于非 DI 解决方案的建议 ( https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/non-di-scenarios ?view=aspnetcore-2.2 )。

Briefly, use static method DataProtectionProvider.Create() for that:简而言之, DataProtectionProvider.Create()使用静态方法DataProtectionProvider.Create()

using Microsoft.AspNetCore.DataProtection;
static class Program
{
    static void Main()
    {
        var dataProtectionProvider = DataProtectionProvider.Create("Test App");
        var protector = dataProtectionProvider.CreateProtector("Program.No-DI");
        var plainText = "ABCDEFGH";
        var protectedText = protector.Protect(plainText);
    }
}

Browsing the sources it seems that instantiating an IDataProtectionProvider without DI can be achieved only through some reflection hacking or code duplicating.浏览来源似乎只能通过一些反射黑客或代码复制来实例化没有 DI 的IDataProtectionProvider

Having a look at this code you can see what implementations are registered for the various interfaces in the DI container.查看此代码,您可以看到为 DI 容器中的各种接口注册了哪些实现。 Eg the implementation for IDataProtectionProvider is KeyRingBasedDataProtectionProvider .例如, IDataProtectionProvider的实现是KeyRingBasedDataProtectionProvider Now check out the source of that class .现在查看该类来源 It's internal so you cannot instantiate it outside the declaring assembly (without reflection).它是内部的,所以你不能在声明程序集之外实例化它(没有反射)。 After some more digging, it turns out that the provider creates KeyRingBasedDataProtector instances which is declared as internal, as well.经过更多的挖掘,事实证明提供者创建了KeyRingBasedDataProtector实例,该实例也声明为内部。

All this suggests that DataProtection API is not intended to be used without a DI container.所有这些都表明 DataProtection API 不打算在没有 DI 容器的情况下使用。 You should reconsider that you really want to use it that way.您应该重新考虑您是否真的想以这种方式使用它。

The use of DI cannot be avoided due to the implementation under the hood.由于在幕后实施,无法避免使用 DI。 If you have a look at the "non DI example" DataProtectionProvider.Create(...) you'll see, that they're using a dedicated composition root just for providing the protector.如果您查看“非 DI 示例” DataProtectionProvider.Create(...)您会看到,他们使用专用组合根仅用于提供保护器。

Inspired by this I wrote this method:受此启发我写了这个方法:

private static IDataProtectionProvider CreateDataProtectionProviderWithPostgresKeyRepository(string connectionString)
{
    var services = new ServiceCollection();
    var builder = services.AddDataProtection();
    
    builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(sp =>
    {
        return new ConfigureOptions<KeyManagementOptions>(options =>
        {
            options.XmlRepository = new PostgresDataProtectionKeyRepository(connectionString);
        });
    });
    
    return services.BuildServiceProvider().GetRequiredService<IDataProtectionProvider>();
}

where PostgresDataProtectionKeyRepository is just a stupid implementation of IXmlRepository used to store the keys in the database.其中PostgresDataProtectionKeyRepository只是用于将密钥存储在数据库中的IXmlRepository的愚蠢实现

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

相关问题 在 asp.net MVC 5(非核心)中使用 IDataProtectionProvider - Using IDataProtectionProvider in asp.net MVC 5 (not core) Asp.net Core IDataProtectionProvider 对于不同的应用程序是不同的? - Asp.net Core IDataProtectionProvider is different for different application? 在 ASP.NET Core 3.1 框架中使用 IDataProtectionProvider 时如何指定加密密钥? - How to specify the encryption key when using the IDataProtectionProvider in ASP.NET Core 3.1 framework? asp.net核心-在应用启动后创建类的实例 - asp.net core - create an instance of a class after the app started ASP.NET Core创建类可以在其中使用DI的类实例-寻找模式建议 - ASP.NET Core Create class instance where class may use DI - looking for pattern advice ASP.NET Core 单例实例与瞬态实例性能 - ASP.NET Core Singleton instance vs Transient instance performance 在 BaseController 上创建 object 实例并在 ASP.NET 核心的整个项目中访问它 - Create object Instance on BaseController and access it on whole project in ASP.NET Core Asp.net 内核。 如果请求查询字符串为空,则创建 [FromQuery] 参数实例 - Asp.net Core. Create [FromQuery] paremeters instance if request querystring is empty ASP.NET 核心“创建”操作 - ASP.NET core "create" action Asp.net 内核为身份创建接口 - Asp.net core create interface for identity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM