I am using VS 2022 with dotnet core web api and below is my code in Program.cs for data protection.
string appName = "My_WebAPI";
var dataProtectionProvider = DataProtectionProvider.Create(appName);
IDataProtector dataProtector = dataProtectionProvider.CreateProtector(ApplicationConstants.ENCRYPTION_KEY);
string DbContext = dataProtector.Unprotect(builder.Configuration.GetConnectionString("DbContext"));
This code works perfectly fine in IIS express, but when I hosted in IIS I get the below error.
Unhandled exception. System.Security.Cryptography.CryptographicException: The key {....} was not found in the key ring. For more information go to http://aka.ms/dataprotectionwarning at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData) at Microsoft.AspNetCore.DataProtection.DataProtectionCommonExtensions.Unprotect(IDataProtector protector, String protectedData)
Please help me to resolve this, I could not find any similar questions in DotNet Core 6. There were changes in "ConfigureServices" from DotNet Core 5 to 6. I managed to make it work for 6 but it worked only in DEBUG mode. After hosting to IIS, did not work.
Also, one more thing observed when I moved the project to a new folder, previously encrypted data were unable to decrypt. Not sure why is it so. I forgot to capture the exception.
EDIT Adding to the above, The data which was encrypted while running in IIS Express were not able to decrypt while running in IIS. Anyone faced the same issue ? I freshly tried to encrypt and decrypt after hosting in IIS it works and no exception found like The key {....} was not found in the key ring But I might have to connect my code base and debug the data which was encrypted from the application hosted in IIS.
Thanks.