What Causes "The payload was invalid" Error in .Net Core 3.1 Application?

Ty Nguyen 1 Reputation point
2021-08-18T19:04:25.56+00:00

We have a .Net Core 3.1 web app that uses Microsoft.AspNetCore.DataProtection version 3.1.0 to encrypt and decrypt data. The application all of the sudden fails to decrypt the data because of the error "The payload was invalid" as seen below:

[2021-08-18 08:12:19 ERR] [FoxCentral.Web.Api.ErrorController] Path: /api/botflows/2. Error: The payload was invalid.
Trace: at Microsoft.AspNetCore.DataProtection.Cng.CbcAuthenticatedEncryptor.DecryptImpl(Byte* pbCiphertext, UInt32 cbCiphertext, Byte* pbAdditionalAuthenticatedData, UInt32 cbAdditionalAuthenticatedData)
at Microsoft.AspNetCore.DataProtection.Cng.Internal.CngAuthenticatedEncryptorBase.Decrypt(ArraySegment1 ciphertext, ArraySegment1 additionalAuthenticatedData)
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)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)

We store the keys in a database using Entity Framework Core and use X509 certificates to protect the keys. Below is how we set up data protection in our app:

var protectionBuilder = services.AddDataProtection();

protectionBuilder.PersistKeysToDbContext<KeysContext>();

protectionBuilder.ProtectKeysWithCertificate(certificates.KeyProtectCertificate)
.UnprotectKeysWithAnyCertificate(certificates.KeyUnprotectCertificates.ToArray());

All the data was encrypted and decrypted on the same server. What causes that decryption failure? How to recover the data?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
{count} votes