I am using Data Protection APIs from .NetCore, while unprotecting payload using DangerousUnprotect() from IPersistedDataProtector, I am getting said error message.
I have created a single instance of protector using CreateProtector("purpose") of IDataProtectionProvider and using it in different APIs to protect() & unprotect() data. Both APIs work fine for all requests made, however after revocation of a key, I am casting dataProtector to IPersistedDataProtector and then it keeps on throwing an error "The provided payload cannot be decrypted because it was not protected with this protection provider."
I understand that the message is valid by code point of view but could not understand what is causing it to throw. I am using the same application name and purpose string.
I have compared instances of protector as well and they are equal with the same data protection provider instance. Can someone please advise on how can this be traced?
target package: Microsoft.AspNetCore.DataProtection(2.1.1)
Also visited issues but do not see any fix/relevant information to this.
// inside .ctor
var services = new ServiceCollection();
services.AddDataProtection().SetApplicationName("ApplicationName");
var serviceProvider = services.BuildServiceProvider();
this.dPProvider = serviceProvider.GetDataProtectionProvider();
this.protector = this.dPProvider.CreateProtector("purpose");
public string Decrypt(string cipherText)
{
try
{
return this.protector.Unprotect(cipherText);
}
catch (Exception exception)
{
var persistedProtector = this.protector as IPersistedDataProtector;
if (persistedProtector == null)
{
throw new Exception($"Protector cannot be null. Also {exception.Message}");
}
// exception is thrown at below line.
var unprotectedPayload = persistedProtector.DangerousUnprotect(Encoding.UTF8.GetBytes(cipherText), true, out var requiresMigration, out var wasRevoked);
if (wasRevoked)
{
return Encoding.UTF8.GetString(unprotectedPayload);
}
throw new CryptographicException($"Invalid operation. Also {exception.Message}", exception);
}
}
stacktrace : at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
csharp var unprotectedPayload = persistedProtector.DangerousUnprotect(WebEncoders.Base64UrlDecode(encryptedWithRevokedKey), true, out var migrate, out var revoked);
– Crystacrystal