tytra
tytra

Reputation: 21

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

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(ArraySegment`1 ciphertext, ArraySegment`1 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?

Upvotes: 1

Views: 8299

Answers (2)

using Microsoft.AspNetCore.DataProtection;


services.AddDataProtection()
            .SetApplicationName("ProjectName")
            .AddKeyManagementOptions(options =>
            {
                options.NewKeyLifetime = new TimeSpan(180, 0, 0, 0);
                options.AutoGenerateKeys = true;
            });

Upvotes: 0

Jason Pan
Jason Pan

Reputation: 21838

I found keys have a 90-day lifetime by default that why you cause the problem.

And I suggest you use IKeyManager to generate a new key, it maybe can help you recover data.

Offical doc:

Automatic key ring refresh

Upvotes: 1

Related Questions