Search code examples
asp.net-mvccertificateazure-web-app-servicex509

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


I have this Helper Method:

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);
...

When I debug (my local machine), everything is OK, but in the production environment, the last sentence CngKey newKey = CngKey.Create(CngAlgorithm2.Rsa, keyParams); throws the following exception: "The system cannot find the file specified."

The main idea is to create a Self-Signed certificate (x509) to store it and use it for signing PDF documents.

Update:

StackTrace (using: 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 (using: 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

Solution

  • Like vcsjones guessed, Azure Web Apps does not load the user profile by default.

    You can enable the user profile by setting the app setting WEBSITE_LOAD_USER_PROFILE = 1 for the site in the portal. That might fix your error