什么原因导致 .Net Core 3.1 应用程序中出现"The payload was invalid"错误?



我们有一个。net Core 3.1 web应用程序,使用Microsoft.AspNetCore.DataProtection版本3.1.0加密和解密数据。由于错误"有效载荷无效",应用程序突然无法解密数据。如下所示:

[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)

我们使用实体框架核心将密钥存储在数据库中,并使用X509证书来保护密钥。下面是我们在应用程序中设置数据保护的方法:

var protectionBuilder = services.AddDataProtection();
protectionBuilder.PersistKeysToDbContext<KeysContext>();
protectionBuilder.ProtectKeysWithCertificate(certificates.KeyProtectCertificate)
.UnprotectKeysWithAnyCertificate(certificates.KeyUnprotectCertificates.ToArray());

所有数据都在同一台服务器上加密和解密。是什么导致了解密失败?如何恢复数据?

我发现密钥默认有90天的生命周期,这就是为什么你会造成这个问题。

我建议你使用IKeyManager生成一个新的密钥,它可能有助于你恢复数据。

官方文档:

键环自动刷新

using Microsoft.AspNetCore.DataProtection;

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

相关内容

最新更新