除了将密钥存储到 azure blob 存储之外,最好的方法是什么?
根据您提供的文档,我们可以将密钥存储在文件系统、Azure Redis、Azure 存储和注册表中。由于 Web Job(Azure Web App)不支持 Registry。如果选择文件系统,我们还需要在 Web Job 和您的 Web 应用程序之间传输密钥。所以 Azure Redis 和 Azure Storage 将是很好的方法。
如果我在正确的轨道上,我该如何存储它?
以下是如何在 Azure 存储上存储密钥的详细步骤。
第 1 步,如果您没有 Azure 存储帐户,则需要创建一个。
第 2 步,使用 NuGet 安装 Microsoft.AspNetCore.DataProtection.AzureStorage 包。
第 3 步,使用以下代码配置 DataProtection。我们需要调用 SetApplicationName 方法并使用与您的 Web Job 相同的应用程序名称。
var storageAccount = CloudStorageAccount.Parse("put your azure storage connection string here");
var client = storageAccount.CreateCloudBlobClient();
var container = client.GetContainerReference("key-container");
container.CreateIfNotExistsAsync().GetAwaiter().GetResult();
services.AddDataProtection().SetApplicationName("myapplication")
.PersistKeysToAzureBlobStorage(container, "keys.xml");
第 4 步,在您的控制器中,您可以使用 IDataProtectionProvider,如下所示。
public class HomeController : Controller
{
private IDataProtector _protector;
public HomeController(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("test-purpose");
}
public IActionResult Index()
{
string encryptedTExt = _protector.Protect("abcd");
return Content(encryptedTExt);
}
}
如何为 webjob 项目配置相同的设置,如没有 Startup.cs 用于配置的链接中所示?
第 1 步,您需要添加对以下 DLL 的引用。

第 2 步,添加 IDataProtector 的包装类,如下所示。
public class EncryptService
{
IDataProtector _protector;
// the 'provider' parameter is provided by DI
public EncryptService(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("test-purpose");
}
public string Protect(string text)
{
return _protector.Protect(text);
}
public string Unprotect(string encryptedText)
{
return _protector.Unprotect(encryptedText);
}
}
第 3 步,使用 ServiceCollection 配置数据保护服务。请注意,我们需要调用 SetApplicationName 方法并使用与您的 Web 应用程序相同的应用程序名称。
static void Main()
{
var storageAccount = CloudStorageAccount.Parse("put your azure storage connection string here");
var client = storageAccount.CreateCloudBlobClient();
var container = client.GetContainerReference("key-container");
container.CreateIfNotExistsAsync().GetAwaiter().GetResult();
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection().SetApplicationName("myapplication")
.PersistKeysToAzureBlobStorage(container, "keys.xml");
var services = serviceCollection.BuildServiceProvider();
}
第 4 步,之后,您可以使用以下代码来加密或解密您的数据。
var encryptService = ActivatorUtilities.CreateInstance<EncryptService>(services);
string text = encryptService.Protect("abcd");