Skip to content

Keyring error when persisting key to registry #60049

Closed
@Julien-Marpault

Description

@Julien-Marpault

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I customized DataProtection to save key to windows registry.
When doing this I get this exception:

fail: Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider[48]
      An error occurred while reading the key ring.
      System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime. (Parameter 't')
         at System.DateTime.ThrowDateArithmetic(Int32 param)
         at System.DateTime.op_Addition(DateTime d, TimeSpan t)
         at System.DateTimeOffset.op_Addition(DateTimeOffset dateTimeOffset, TimeSpan timeSpan)
         at Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver.<>c__DisplayClass6_0.<FindDefaultKey>b__3(IKey key)
         at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
         at Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver.FindDefaultKey(DateTimeOffset now, IEnumerable`1 allKeys, IKey& fallbackKey, Boolean& callerShouldGenerateNewKey)
         at Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver.ResolveDefaultKeyPolicy(DateTimeOffset now, IEnumerable`1 allKeys)
         at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider.CreateCacheableKeyRingCore(DateTimeOffset now, IKey keyJustAdded)
         at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider.GetCurrentKeyRingCore(DateTime utcNow, Boolean forceRefresh)

Here's my code:

public static IServiceCollection AddDataProtectionKeysToWindowsRegistry(this IServiceCollection services)
    {
        RegistryKey registreyKey = Registry.CurrentUser.CreateSubKey(@"Software\Test\keys", true);

        services.AddDataProtection()
            .SetApplicationName(DataProtectionKeysOptions.ApplicationName)
            .PersistKeysToRegistry(registreyKey)
            .ProtectKeysWithDpapi();

        return services;
    }

Removing PersistKeysToRegistry() makes things working.
Removing ProtectKeysWithDpapi() doesn't change anything.

Expected Behavior

No response

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version

8.0.404

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs: Attention 👋This issue needs the attention of a contributor, typically because the OP has provided an update.area-dataprotectionIncludes: DataProtection

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions