使用 Entity Framework 核心的数据保护

Data Protection using Entity Framework Core

所以我按照微软的官方指南(https://docs.microsoft.com/el-gr/aspnet/core/security/data-protection/implementation/key-storage-providers?view=aspnetcore-2.2&tabs=visual-studio)使用 Entity Framework Core 加密数据并将它们存储在数据库中,但我无法让它在多台机器上工作。所以我使用了 Entity Framework 核心实现,因为在指南中说 "With this package, keys can be shared across multiple instances of a web app."。从已部署版本(例如 xyz.com)使用该应用程序时,该应用程序可以完美运行,但它不会让我干扰本地主机。当我的虚拟机用完并且我想添加另一个时,以后会不会有问题?如果是这样,我怎样才能让它在部署的站点和不同的机器上工作?没有实现它的教程,我到处搜索。非常感谢。

services.AddDataProtection()
                .UseCryptographicAlgorithms(
                    new AuthenticatedEncryptorConfiguration()
                    {
                        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
                        ValidationAlgorithm = ValidationAlgorithm.HMACSHA256,

                    }
                ).PersistKeysToDbContext<DataContext>();

2019 年 12 月 6 日更新

所以我遵循了微软的文档 (https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-encryption-at-rest?view=aspnetcore-2.2) 它指出:

"If the app is spread across multiple machines, it may be convenient to distribute a shared X.509 certificate across the machines and configure the hosted apps to use the certificate for encryption of keys at rest"

我使用本教程生成了 x.509 证书:

(https://www.youtube.com/watch?v=1xtBkukWiek)

我更新的代码:

        services.AddDataProtection()
                .UseCryptographicAlgorithms(
                    new AuthenticatedEncryptorConfiguration()
                    {
                        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
                        ValidationAlgorithm = ValidationAlgorithm.HMACSHA256,

                    }
                )
                // )
                .ProtectKeysWithCertificate(new X509Certificate2("wibit-test-cert.pfx", "password"))
                .PersistKeysToDbContext<DataContext>();

在我的本地机器上测试时它工作正常,但是当我部署它时,我得到这个错误:

错误:"The system cannot find the file specified"

我尝试了多种方法来修复它,包括 _hostingEnvironment.ContentRootPath 或 WebRootPath。这两种方式和我在更新代码中使用的方式都适用于我的机器,但不适用于已部署的应用程序。

有什么线索吗?

我终于修好了! 问题是我没有设置应用程序名称:

.SetApplicationName("myapp")

并且我将证书的路径更改为:

.ProtectKeysWithCertificate(new X509Certificate2(Path.Combine(_hostingEnvironment.ContentRootPath,"wibit-test-cert.pfx"), "password"))

也可能是权限问题,因为当我在 A2Hosting 中托管应用程序时,它找不到指定的文件 (wibit-test-cert.pfx),但是当我在 GCP Cloud 中部署时,它工作正常!

现在我可以通过不同的应用程序使用同一个数据库来加密和解密数据。

所以我的最终代码是这样的:

services.AddDataProtection()
  .UseCryptographicAlgorithms(
      new AuthenticatedEncryptorConfiguration()
         {
             EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
             ValidationAlgorithm = ValidationAlgorithm.HMACSHA256,

          }
       )
       .SetApplicationName("myapp")
       .ProtectKeysWithCertificate(new X509Certificate2(Path.Combine(_hostingEnvironment.ContentRootPath,"wibit-test-cert.pfx"), "password"))
       .PersistKeysToDbContext<DataContext>();