.NET 标准 2.0 和 System.Security.Cryptography.ProtectedData.Protect

.NET Standard 2.0 and System.Security.Cryptography.ProtectedData.Protect

我在看System.Security.Cryptography.ProtectedData.Protect @https://docs.microsoft.com/en-gb/dotnet/api/

因为我们希望将库从 .NET Framework 4.7 移植到 .NET Standard 2.0 以供 .NET Core 2.0 使用。 我进行了搜索,它仅在完整的 .NET Framework 和 .NET Core 中可用。

我的问题是,为什么它在 .NET Standard 2.0 中不可用?

我原以为如果它可以用于 .NET Framework 4.7 和 .NET Core 2.0,那么它也会成为 .NET Standard 2.0 的一部分

首先

我无法为微软回答

tl;博士

其中很多问题都可以通过以下方式回答:如果您需要在 .NET Framework 中找到的 API,请使用 .NET Framework。

更长的答案

.NET Framework 中发现的大量 API 要么依赖于底层 Windows 库(MacO 或 Linux 发行版不可用),要么它们是目前实施起来太复杂,因此它们不适用于 .NET Core。

如果 API 您需要访问仅在 .NET Framework 中可用的内容,那么(目前)最好使用 .NET Framework 而不是 .NET Core/Mono/etc .

如果您有令人信服的理由要求将某些内容包含在 .NET Standard 中,那么我会前往 .NET Standard GitHub repo 并要求在那里实施它。

此 API 不可用 "in" .NET Standard 2.0,但可用 "for" .NET Standard 2.0 作为 "Platform Extension" 这意味着有一个您必须添加 NuGet 包才能获得对它的支持。

如果添加对 System.Security.Cryptography.ProtectedData NuGet 包的引用,则可以开发使用这些 API 的 .NET Standard 库。

但是,此支持仅在 Windows 上的 运行 时有效,因为那些 API 被描述为

Provides access to Windows Data Protection Api.

所以它不能在 Windows 以外的平台上运行。根据您的需要,这可能就好了。

如果您希望跨平台实现类似的概念,我建议查看 ASP.NET Core Data Protection APIs,它也可以在 ASP.NET 核心应用程序的上下文之外使用,因为它是由提供加密逻辑和密钥存储解决方案的 NuGet 包(例如目录、windows 证书存储、Azure KeyVault)。

ProtectedData 使用 DPAPI from Windows. I created the library CrossProtectedData,在 Windows 中使用 ProtectedData,在 Windows 中使用 AspNetCore.DataProtection,在非 Windows 中使用 AspNetCore.DataProtection。

要使用,只需添加 NuGet 包 CrossProtect 并将对 ProtectedData 的任何调用替换为 CrossProtect。示例:

using Integrative.Encryption;
using System;
using System.Security.Cryptography;
using System.Text;

namespace CrossProtectedExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // our text to protect
            var text = "Hello!";

            // get bytes from text
            var bytes = Encoding.UTF8.GetBytes(text);

            // optional entropy
            var entropy = new byte[] { 100, 25, 31, 213 };

            // protect (encrypt)
            var protectedBytes = CrossProtect.Protect(bytes, entropy,
                DataProtectionScope.CurrentUser);

            // unprotect (decrypt)
            var unprotected = CrossProtect.Unprotect(protectedBytes, entropy,
                DataProtectionScope.CurrentUser);

            // convert bytes back to text
            var result = Encoding.UTF8.GetString(unprotected);

            // print result
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}