Skip to content

Reduce allocations in managed DataProtection protect/unprotect - #70146

Merged
DeagleGross merged 7 commits into
mainfrom
perf/dataprotection-managed-encryptor-allocs
Nov 5, 2026
Merged

DeagleGross merged 7 commits into
mainfrom
perf/dataprotection-managed-encryptor-allocs

Conversation

@davidfowl

@davidfowl davidfowl commented Oct 30, 2026 •

Copy link
Copy Markdown
Member
  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making.

Reduce allocations in the managed DataProtection Protect/Unprotect path.

Description

  • ManagedAuthenticatedEncryptor now uses a single SymmetricAlgorithm instance to both size and perform the encryption. Previously each Protect created up to three, and one of them was never disposed. It also implements IOptimizedAuthenticatedEncryptor, so the payload is encrypted directly into the final array, including the key-ring header pre-buffer.
  • ManagedSP800_108_CTR_HMACSHA512 keeps the 128-byte stack buffer for the PRF input. Above that it now rents from ArrayPool (cleared on return) instead of allocating. Real purpose chains, such as application discriminator plus cookie authentication purposes, exceed 128 bytes, so every Protect and Unprotect used to allocate here.
  • The output bytes are unchanged; a known-answer test checks this.

Benchmark (new KeyRingProtectorBenchmarks, 200 B plaintext, BDN InProcess, 3 interleaved rounds against main, Linux; mean of the round means):

Method main This PR
Protect_ShortPurpose 10.09 us / 1480 B 9.44 us / 640 B
Unprotect_ShortPurpose 7.44 us / 720 B 7.51 us / 544 B
Protect_CookiePurpose 10.06 us / 1552 B 9.44 us / 640 B
Unprotect_CookiePurpose 7.39 us / 792 B 7.45 us / 544 B

Protect is about 6% faster. Unprotect is within run-to-run noise (+0.7 to 0.9%, round spread about 0.1 us). Allocations drop 57-59% on Protect and 24-31% on Unprotect. The Antiforgery token serializer benefits as well: Serialize goes from 1160 to 784 B and Deserialize from 776 to 584 B.

Tests: Microsoft.AspNetCore.DataProtection.Tests (net12.0), 344 passed. The 7 new tests are a KDF comparison against a reference SP800-108 implementation across the stack threshold, and a known-answer encrypt with pre- and post-buffers. net472 builds.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

Copilot AI balanced review requested due to automatic review settings October 30, 2026 22:57
@github-actions github-actions Bot added the area-dataprotection Includes: DataProtection label Oct 30, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues block approval of the Data Protection allocation-reduction changes.

No open issues 🎉

What changed in this PR

This PR reduces allocations in managed Data Protection protect/unprotect operations while preserving the encrypted payload format.

Changes:

  • Reuses one symmetric algorithm instance per encryption and writes directly into the final output array.
  • Raises the key-derivation stack buffer threshold to avoid heap allocations for common purpose chains.
  • Adds compatibility tests and benchmarks for short and cookie-authentication purpose chains.
File Description
src/​DataProtection/​DataProtection/​test/​Microsoft.AspNetCore.DataProtection.Tests/​SP800_108/​SP800_108Tests.cs Compares key derivation against a reference implementation across buffer thresholds.
src/​DataProtection/​DataProtection/​test/​Microsoft.AspNetCore.DataProtection.Tests/​Managed/​ManagedAuthenticatedEncryptorTests.cs Adds known-answer and round-trip coverage with pre- and post-buffers.
src/​DataProtection/​DataProtection/​src/​SP800_108/​ManagedSP800_108_CTR_HMACSHA512.cs Increases the stack buffer threshold from 128 to 512 bytes.
src/​DataProtection/​DataProtection/​src/​Managed/​ManagedAuthenticatedEncryptor.cs Reuses the algorithm instance and supports direct encryption into the final array.
src/​DataProtection/​benchmarks/​Microsoft.AspNetCore.DataProtection.MicroBenchmarks/​Benchmarks/​KeyRingProtectorBenchmarks.cs Adds protect/unprotect allocation benchmarks for representative purpose chains.

Review effort: Balanced

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-ci

Rerunning: the only failure is BlazorWebTemplate_ConditionalPasskeyRegistration on Windows (known flaky, 6.35% failure rate per Build Analysis, tracked in #69494). It is unrelated to this change, which only touches the managed (non-CNG) encryptor.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-ci

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

@davidfowl
davidfowl force-pushed the perf/dataprotection-managed-encryptor-allocs branch from 36942b2 to ec9ec16 Compare October 31, 2026 00:23
- ManagedAuthenticatedEncryptor: use a single SymmetricAlgorithm instance for
  sizing and encryption (previously up to 3 per Protect, one never disposed),
  and implement IOptimizedAuthenticatedEncryptor so the payload is encrypted
  directly into the final array including the key ring header pre-buffer.
- ManagedSP800_108_CTR_HMACSHA512: raise PRF input stackalloc threshold from
  128 to 512 bytes. AAD (app discriminator + purposes) routinely pushes the
  input above 128 bytes, causing a heap allocation per Protect/Unprotect.
- Add KeyRingProtectorBenchmarks and tests.

Co-authored-by: Copilot <[email protected]>
@davidfowl
davidfowl force-pushed the perf/dataprotection-managed-encryptor-allocs branch from ec9ec16 to cd564d7 Compare October 31, 2026 01:40

Copy link
Copy Markdown
Member Author

CI note: across two runs on identical content (36942b2, ec9ec16), every job passed at least once. Run 1 failed only BlazorWebTemplate_ConditionalPasskeyRegistration on Windows (known flaky, #69494), and run 2 failed only the Helix job monitor (Helix passed in run 1). I re-pushed the same commit to rerun CI.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

davidfowl and others added 2 commits October 31, 2026 10:32
- Replace Unsafe.AreSame/MemoryMarshal assert with a safe Span.Overlaps check
  and drop the now-unused usings.
- Keep the SP800-108 PRF input stackalloc at 128 bytes; rent from ArrayPool
  (cleared on return) above that instead of heap-allocating.

Co-authored-by: Copilot <[email protected]>
…be rented

The 0x00 separator between label and context was never written and relied on a
zero-initialized buffer. Pooled arrays are not zeroed, which produced wrong
subkeys (seen as cookie auth failures in AuthSamples.FunctionalTests). Write it
explicitly and make the reference test leave dirty data in the pool first.

Co-authored-by: Copilot <[email protected]>

Copy link
Copy Markdown
Member Author

The CI failure on 7448283 (AuthSamples cookie tests on macOS/Linux) was a real bug in that commit and is fixed in 782440c. Switching the >128-byte PRF input from new byte[] to an ArrayPool rental exposed that the SP800-108 0x00 separator after the label was never written explicitly; it relied on a zeroed buffer, so a dirty pooled array produced wrong subkeys. The separator is now written explicitly. DeriveKeys_Managed_LongLabel_MatchesReferenceImplementation now leaves dirty data in the pool first: it fails without the fix and passes with it. Locally, DataProtection.Tests passes (344) and AuthSamples.FunctionalTests passes 30/30 (6 failed before the fix).

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@PureWeen

PureWeen commented Nov 1, 2026

Copy link
Copy Markdown
Member

/review

Copy link
Copy Markdown
Member Author

CI is fully green on 782440c, which includes the explicit SP800-108 separator fix: aspnetcore-ci and aspnetcore-quarantined-pr pass on every job, with no reruns needed. The automated review raised no open issues. This is ready for maintainer review.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

davidfowl and others added 2 commits November 1, 2026 12:49
…arks

On Windows the default AES-256-CBC/HMACSHA256 key maps to the CNG encryptor,
and the benchmark reused the user-profile key ring. Use
ManagedAuthenticatedEncryptorConfiguration with a temp key directory so
ManagedAuthenticatedEncryptor is measured on every OS.

Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>

Copy link
Copy Markdown
Member Author

I retriggered CI with an empty commit, 29ebe73. CI on 116f518 had one failure: Microsoft.AspNetCore.Mvc.FunctionalTests.RealServerUsingMinimalBackedIntegrationTests.CanResolveServices on Ubuntu.2404, which threw System.InvalidOperationException: IServerAddressesFeature.Addresses cannot be modified after the server has started. from WebApplicationFactory.TryConfigureServerPort. Build Analysis gives it a 0.63% historical failure rate. It's a timing issue in the MVC testing host's Kestrel address setup and is unrelated to this PR, which only changes the managed DataProtection encryptor, the SP800-108 KDF, their tests and a benchmark. Every other job passed.

🤖 Posted by ASP.NET Core Perf 2 (AI Agent)

@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 5, 2026 — with Copilot SWE Agent
…tor round-trip tests

The PRF input contains key derivation material, so don't place it in shared pooled
memory. Raise the constant stack buffer to 256 bytes to cover longer AAD (purpose)
values and fall back to a new array above that.

Add tests that go through AuthenticatedEncryptorExtensions.Encrypt (IOptimizedAuthenticatedEncryptor)
and KeyRingBasedDataProtector.Protect/Unprotect with a real managed CBC encryptor, with
cases on both sides of the 128- and 256-byte KDF input thresholds.

Co-authored-by: Copilot <[email protected]>
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 5, 2026
@davidfowl davidfowl added the agent:working An AI agent is actively working on this issue/PR label Nov 5, 2026 — with Copilot SWE Agent
@davidfowl davidfowl removed the agent:working An AI agent is actively working on this issue/PR label Nov 5, 2026
@DeagleGross
DeagleGross enabled auto-merge (squash) November 5, 2026 17:22
@DeagleGross
DeagleGross merged commit 70dc164 into main Nov 5, 2026
27 checks passed
@DeagleGross
DeagleGross deleted the perf/dataprotection-managed-encryptor-allocs branch November 5, 2026 18:24
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 5%

No docs needed: internal performance refactoring of managed DataProtection with no observable behavior change.

Documentation surfaces considered

  • Conceptual article: Not required — Internal allocation optimization; no public API, configuration, or behavior change (signals: no_signal).
  • Migration guidance: Not required — No user action needed when upgrading; output bytes are unchanged.
  • Breaking change: Not required — No compatibility impact; payload format unchanged and verified by known-answer test.

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 1cf55758 Deployed Nov 5, 2026 by DeagleGross via conclusion #201
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-dataprotection Includes: DataProtection

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants