使用 Azure Web 应用程序 (ASP.NET MVC 5) 在 .NET 中创建自签名证书

Create a Self-Signed Certificate in .NET, using an Azure Web Application (ASP.NET MVC 5)

我有这个辅助方法:

CngKeyCreationParameters keyParams = new CngKeyCreationParameters();
keyParams.KeyCreationOptions = CngKeyCreationOptions.None;
keyParams.KeyUsage = CngKeyUsages.Signing;
keyParams.Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider;
keyParams.ExportPolicy = CngExportPolicies.AllowExport;
String newguid = Guid.NewGuid().ToString();
CngKey newKey = CngKey.Create(CngAlgorithm2.Rsa, keyParams);
...

我调试的时候(我的本机)一切正常,但是在生产环境中,最后一句CngKey newKey = CngKey.Create(CngAlgorithm2.Rsa, keyParams);抛出如下异常:"The system cannot find the file specified."

主要思想是创建一个自签名证书 (x509) 来存储它并使用它来签署 PDF 文档。

更新:

StackTrace(使用:CngKeyCreationOptions.None):

[CryptographicException: The system cannot find the file specified.
]
   System.Security.Cryptography.NCryptNative.CreatePersistedKey(SafeNCryptProviderHandle provider, String algorithm, String name, CngKeyCreationOptions options) +2244958
   System.Security.Cryptography.CngKey.Create(CngAlgorithm algorithm, String keyName, CngKeyCreationParameters creationParameters) +248

StackTrace(使用:CngKeyCreationOptions.MachineKey):

[CryptographicException: Access denied.
]
   System.Security.Cryptography.NCryptNative.FinalizeKey(SafeNCryptKeyHandle key) +2243810
   System.Security.Cryptography.CngKey.Create(CngAlgorithm algorithm, String keyName, CngKeyCreationParameters creationParameters) +266

正如 vcsjones 猜测的那样,Azure Web Apps 默认不加载用户配置文件。

您可以通过在门户中为站点设置应用程序设置 WEBSITE_LOAD_USER_PROFILE = 1 来启用用户配置文件。这可能会解决您的错误