Feedemy.KeyManagement.Providers.EntityFramework
4.0.0
dotnet add package Feedemy.KeyManagement.Providers.EntityFramework --version 4.0.0
NuGet\Install-Package Feedemy.KeyManagement.Providers.EntityFramework -Version 4.0.0
<PackageReference Include="Feedemy.KeyManagement.Providers.EntityFramework" Version="4.0.0" />
<PackageVersion Include="Feedemy.KeyManagement.Providers.EntityFramework" Version="4.0.0" />
<PackageReference Include="Feedemy.KeyManagement.Providers.EntityFramework" />
paket add Feedemy.KeyManagement.Providers.EntityFramework --version 4.0.0
#r "nuget: Feedemy.KeyManagement.Providers.EntityFramework, 4.0.0"
#:package Feedemy.KeyManagement.Providers.EntityFramework@4.0.0
#addin nuget:?package=Feedemy.KeyManagement.Providers.EntityFramework&version=4.0.0
#tool nuget:?package=Feedemy.KeyManagement.Providers.EntityFramework&version=4.0.0
Feedemy.KeyManagement
Enterprise-grade key management library for .NET applications.
Features
- Automatic Key Rotation - Background service with configurable intervals
- Versioned Encryption - Auto-decryption with version detection
- Asymmetric Keys - RSA (2048/3072/4096) and ECDSA (P-256/P-384/P-521): signing that names its version and
kid, a JWKS-ready verification key set, rotations published before use and verifiable after, RSA-OAEP by version - Multi-Platform Storage - Windows DPAPI, Linux Keyring, Azure Key Vault
- Distributed Caching - Redis with pub/sub invalidation
- Database Persistence - SQL Server and PostgreSQL
- Health Monitoring - ASP.NET Core health checks
- Fallback Storage - Multi-provider redundancy
- Audit Trail - Fail-closed, hash-chained audit with chain verification and export
- Typed Admin API - Commands with preconditions (ETag), idempotency keys, validate-only plans and a host authorization hook
- Wrapped Import - Import key material wrapped for a single-use RSA-3072 import job
- Roslyn Analyzers - 47 compile-time rules (21 raised)
Installation
dotnet add package Feedemy.KeyManagement
# Persistence (choose one)
dotnet add package Feedemy.KeyManagement.Providers.EntityFramework # SQL Server
dotnet add package Feedemy.KeyManagement.Providers.Npgsql # PostgreSQL
# Optional
dotnet add package Feedemy.KeyManagement.Analyzers
Upgrading to 4.0? 4.0 is a clean break: the 3.x interfaces, their result and request types and the
[Obsolete]builder methods are gone, and schema migrationV2.0.0is one-way. Coming from 3.5.x (3.6.0 and 3.7.0 were not published), in this order: stop every 3.x node; back up the database; removeEnlist=falsefrom the KeyManagement connection string (registration refuses it); runDatabaseMigratorfrom the host and stop on a failure (it refuses rows 4.0 could not write back - the guide has the SQL to fix them); delete no fallback*.keyfile (3.x wrote decrypted key material there; 4.0 rebuilds a fallback store at every start, and a node left atAutoholds its only key copy in those files); start the 4.0 nodes (the first migrates the schema:V2.0.0, then the additiveV2.1.0andV2.2.0) and, with fallback storage, check each node's startup sync log line; let the background material upgrade rewrite the material stored before 4.0, and onceSystemHealth.MaterialUpgradePendingis 0 setAsymmetric.AllowLegacyMaterialEnvelope = false. A key definition file'skeyTypemust be one of the accepted names (another value stops the start). A backup tool that decrypts without the database moves to the opt-in recovery read (WithRecoveryReads(), key initialization off). Read the Migration Guide and the CHANGELOG ([4.0.0], Upgrade) first.
Quick Start
Development Setup
using Feedemy.KeyManagement.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddKeyManagement(options =>
{
options.EnableAutoRotation = true;
options.RotationCheckInterval = TimeSpan.FromHours(6);
})
.UseDevelopmentDefaults(); // in-memory key storage, cache and metadata: everything is lost on restart
var app = builder.Build();
app.Run();
Production Setup
builder.Services.AddKeyManagement(options =>
{
options.EnableAutoRotation = true;
options.RotationCheckInterval = TimeSpan.FromHours(6);
// Auto-initialization
options.Initialization.EnableAutoInitialization = true;
options.Initialization.ExternalKeysJsonPath = "keys.json";
})
.WithAzureKeyStorage("https://your-vault.vault.azure.net/")
.WithRedisCache("localhost:6379")
.WithSqlServerMetadata(connectionString);
builder.Services.AddHealthChecks()
.AddKeyManagementHealthCheck();
The library migrates its schema at startup, before anything else of it touches the metadata store (a major
migration copies the tables into a backup schema first). An application account without DDL rights hands the step
a migration account; a database a DBA migrates only checks the version at startup and runs DatabaseMigrator itself:
builder.Services.AddKeyManagement()
.WithSqlServerMetadata(appConnectionString)
.WithSchemaMigration(SchemaMigrationMode.Automatic, migrationConnectionString); // or SchemaMigrationMode.Validate
// With Validate, from a deployment step:
var migration = await new DatabaseMigrator(connectionString).MigrateAsync();
if (!migration.Success)
{
throw new InvalidOperationException($"Key management migration failed: {migration.ErrorMessage}");
}
Basic Usage
The API is split by plane: IKeyMaterialService serves key material and IAsymmetricKeyOperations signs,
verifies and encrypts with RSA and ECDSA keys (the data plane), IKeyCatalog, IKeyEndorsementCatalog and
IKeyAuditLog read, and IKeyAdministration and IKeyEndorsementCommands change things. Every command takes
CommandOptions (who, why, IfMatch, idempotency key, validate-only) and returns a CommandResult<T>.
using System.Security.Cryptography;
using Feedemy.KeyManagement.Contracts;
using Feedemy.KeyManagement.Core.Abstractions;
public class MyService(IKeyAdministration admin, IKeyMaterialService material, IKeyCatalog catalog)
{
// Create a key: the library generates a 256-bit symmetric key
public async Task<KeyDetails> CreateKeyAsync(CancellationToken ct)
{
var result = await admin.CreateKeyAsync(
new CreateKey
{
Name = "MyEncryptionKey",
Spec = new KeySpec { Kind = KeyType.Symmetric },
Material = KeyMaterialSource.Generate,
Rotation = new RotationPolicy { IntervalDays = 90, Automatic = true }
},
new CommandOptions
{
Actor = new Actor { Id = "admin@example.com", Kind = ActorKind.User },
Reason = "Initial setup"
},
ct);
if (!result.IsSuccess)
{
throw new InvalidOperationException($"{result.Error!.CodeString}: {result.Error.Message}");
}
return result.Value!;
}
// Read the current material (cached in process memory)
public async Task UseKeyAsync(CancellationToken ct)
{
var lookup = await material.GetMaterialAsync("MyEncryptionKey", ct);
if (lookup.Status != MaterialStatus.Found)
{
throw new InvalidOperationException($"Key unavailable: {lookup.Status}");
}
try
{
Encrypt(lookup.Content!, lookup.Version); // store the version with the ciphertext
}
finally
{
CryptographicOperations.ZeroMemory(lookup.Content); // the copy is the caller's
}
}
// Rotate, guarded by the ETag the operator saw
public Task<CommandResult<VersionChange>> RotateAsync(string etag, string idempotencyKey, CancellationToken ct) =>
admin.RotateKeyAsync("MyEncryptionKey", new RotateKey(),
new CommandOptions
{
Actor = new Actor { Id = "admin@example.com" },
Reason = "Quarterly rotation",
IfMatch = etag, // PRECONDITION_FAILED if the key changed since it was read
IdempotencyKey = idempotencyKey // a retry with the same value does not rotate twice
},
ct);
// Check health
public async Task<KeyHealthStatus?> GetHealthAsync(CancellationToken ct) =>
(await catalog.GetKeyHealthAsync("MyEncryptionKey", ct))?.Status;
private static void Encrypt(byte[] key, int version) { /* your AES-GCM code */ }
}
A symmetric key is envelope-encrypted with the master key by default (CreateKey.MasterKeyEncrypted); the
startup service creates the master key when it is missing (AutoBootstrapMasterKey, default on), and adopts the
master key's material when key storage already holds it but the metadata store does not (a UseLocalDefaults()
restart, or a lost database whose replacement is pointed at the old installation folder) instead of writing a new one
over it.
Key Initialization
Define keys in keys.json for auto-generation on first run:
{
"Keys": [
{
"KeyName": "EncryptionKey",
"KeyType": "Symmetric",
"RotationIntervalDays": 90,
"Category": "MasterKey"
},
{
"KeyName": "JwtSigningKey",
"KeyType": "RSA",
"KeySize": 2048,
"RotationIntervalDays": 180,
"Category": "Signing"
}
]
}
Asymmetric Keys
// Sign: data is the signing input (the library hashes it); the result names the version and kid that signed
var signed = await asymmetric.SignAsync("JwtSigningKey", signingInput, SignatureAlgorithm.RS256, ct: ct);
if (signed.Status == SigningStatus.Signed) { /* signed.Signature, signed.Kid for the JWS header */ }
// Verify against the key's verification set: current, upcoming, previous versions within their grace
var verified = await asymmetric.VerifyAsync("JwtSigningKey", kid, signingInput, signature, SignatureAlgorithm.RS256, ct: ct);
// JWKS endpoint
var set = await asymmetric.GetVerificationKeysAsync("JwtSigningKey", ct);
var jwks = new { keys = set.Keys.Select(k => k.Jwk) };
The private key stays in the library: it is not served by GetMaterialAsync and leaves only through the opt-in
export (KeyManagementOptions.Asymmetric.AllowPrivateKeyExport). A key's PublicationPolicy publishes each new
version before it signs and keeps the old one verifiable after it (docs/API.md).
Warm sign, verify and key set calls touch no store and import no key; measured costs (RS256 / ES256, against 3.x) are in
docs/claude/benchmarks/asymmetric/hot-path/sign-verify.md.
Packages
| Package | Description |
|---|---|
Feedemy.KeyManagement |
Core library |
Feedemy.KeyManagement.Providers.EntityFramework |
SQL Server persistence |
Feedemy.KeyManagement.Providers.Npgsql |
PostgreSQL persistence |
Feedemy.KeyManagement.Analyzers |
Roslyn analyzers |
Documentation
- docs/API.md - API reference (4.0)
- docs/MIGRATION_GUIDE.md - Upgrading, including the 3.x → 4.0 member mapping
- docs/CONFIGURATION.md and docs/OPTIONS_REFERENCE.md - Configuration
- docs/ARCHITECTURE.md - Architecture
- docs/TELEMETRY.md and docs/ANALYZER_RULES.md - Telemetry and analyzers
More in docs/partial/:
README_CORE.md- Core services guideREADME_CONFIG.md- Configuration optionsREADME_STORAGE.md- Storage providersREADME_PERSISTENCE.md- Database setupREADME_CACHE.md- Caching architectureREADME_INIT.md- Initialization guideREADME_BACKGROUND.md- Background servicesREADME_EXTENSIONS.md- DI setup
License
This project is dual-licensed:
- MIT License - Free for all use cases including commercial
- Commercial License - For enterprise support, SLA, and priority features
| Use Case | License | Cost |
|---|---|---|
| Personal projects | MIT | Free |
| Open source projects | MIT | Free |
| Commercial products | MIT | Free |
| Enterprise support & SLA | Commercial | Paid |
Commercial inquiries: licensing@feedemy.com
Support
Copyright (c) 2025 Feedemy
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Feedemy.KeyManagement (>= 4.0.0)
- Microsoft.EntityFrameworkCore (>= 10.0.11)
- Microsoft.EntityFrameworkCore.Relational (>= 10.0.11)
- Microsoft.EntityFrameworkCore.SqlServer (>= 10.0.11)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 4.0.0 | 48 | 11/24/2026 |
| 3.5.0 | 210 | 10/11/2026 |
| 3.4.0 | 170 | 9/6/2026 |
| 3.3.1 | 469 | 8/27/2026 |
| 3.3.0 | 554 | 6/11/2026 |
| 3.2.1 | 227 | 4/24/2026 |
| 3.2.0 | 141 | 4/24/2026 |
| 3.1.0 | 199 | 3/9/2026 |
| 3.0.6 | 156 | 3/9/2026 |
| 3.0.5 | 142 | 3/9/2026 |
| 3.0.4 | 135 | 3/9/2026 |
| 3.0.3 | 173 | 3/9/2026 |
| 3.0.2 | 144 | 3/9/2026 |
| 3.0.1 | 145 | 2/27/2026 |
| 2.5.10 | 312 | 1/21/2026 |
| 2.5.3 | 256 | 1/3/2026 |
| 2.5.2 | 744 | 12/1/2025 |
| 2.5.1 | 741 | 12/1/2025 |
v4.0.0 - Aligned to Feedemy.KeyManagement 4.0.0 (admin and read API surface)
Schema V2.3.0: KeyAlarms and two endorsement indexes; IKeyAlarmRepository and the operations views' repository members.
Breaking, with schema V2.0.0: a one-way upgrade. Stop every 3.x node, back
up the database, run DatabaseMigrator, then start the 4.0 nodes. Mixed
3.x/4.0 fleets are unsupported; going back is a database restore.
- The repositories implement the 4.0 persistence contracts: keyset query
methods (the unused paged and load-all reads are gone), key labels (the
KeyLabels table), key and version states, the hash-chained audit
(Sequence and hash columns, the AuditChainHead row locked with UPDLOCK,
ROWLOCK, HOLDLOCK), and the new idempotency, endorsement request and
import job repositories.
- Timestamps are DateTimeOffset; the datetime2(7) columns stay, behind a
value converter that writes and reads UTC.
- KeyLabels.Key and Value are binary (Latin1_General_100_BIN2) whatever
the database's collation, so label keys and the label filter compare as
the commands do.
- A connection string with Enlist=false is refused at registration
(InvalidOperationException): a change and its audit rows commit in one
TransactionScope, which only an enlisting connection joins.
- The V2.0.0 script runs as one transaction, under the migrator's
sp_getapplock.
- Removed: the obsolete UseEntityFrameworkPersistence builder methods (use
WithSqlServerMetadata or AddEntityFrameworkPersistence).
Earlier releases (full notes: CHANGELOG.md in the repository)
v3.7.0 (not published to NuGet) - DuplicateKeyException on a
unique-constraint violation, batched active-version reads, the
rotation-due index aligned to V1.2.0.
v3.6.0 (not published to NuGet) - Batched pending-version reads; unknown
audit actions read as Unknown.
v3.5.0 - Key endorsement storage (KeyEndorsements table, migration V1.4.0).
v3.3.1 and earlier - dependency maintenance; the 3.0.0 alignment (.NET 10,
EF Core 10, parameterized SQL).