Feedemy.KeyManagement 4.0.0

dotnet add package Feedemy.KeyManagement --version 4.0.0
                    
NuGet\Install-Package Feedemy.KeyManagement -Version 4.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Feedemy.KeyManagement" Version="4.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Feedemy.KeyManagement" Version="4.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Feedemy.KeyManagement" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Feedemy.KeyManagement --version 4.0.0
                    
#r "nuget: Feedemy.KeyManagement, 4.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Feedemy.KeyManagement@4.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Feedemy.KeyManagement&version=4.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Feedemy.KeyManagement&version=4.0.0
                    
Install as a Cake Tool

Feedemy.KeyManagement

NuGet License: MIT .NET

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 migration V2.0.0 is 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; remove Enlist=false from the KeyManagement connection string (registration refuses it); run DatabaseMigrator from 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 *.key file (3.x wrote decrypted key material there; 4.0 rebuilds a fallback store at every start, and a node left at Auto holds its only key copy in those files); start the 4.0 nodes (the first migrates the schema: V2.0.0, then the additive V2.1.0 and V2.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 once SystemHealth.MaterialUpgradePending is 0 set Asymmetric.AllowLegacyMaterialEnvelope = false. A key definition file's keyType must 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

More in docs/partial/:

  • README_CORE.md - Core services guide
  • README_CONFIG.md - Configuration options
  • README_STORAGE.md - Storage providers
  • README_PERSISTENCE.md - Database setup
  • README_CACHE.md - Caching architecture
  • README_INIT.md - Initialization guide
  • README_BACKGROUND.md - Background services
  • README_EXTENSIONS.md - DI setup

License

This project is dual-licensed:

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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on Feedemy.KeyManagement:

Package Downloads
Feedemy.KeyManagement.Providers.EntityFramework

Entity Framework Core persistence provider for Feedemy.KeyManagement. Provides SQL Server storage for key metadata, versions, labels, endorsements, idempotency records and the hash-chained audit log; the schema comes from the core package's host-run DatabaseMigrator.

Feedemy.KeyManagement.Providers.Npgsql

PostgreSQL (Npgsql) persistence provider for Feedemy.KeyManagement. Provides PostgreSQL storage for key metadata, versions, labels, endorsements, idempotency records and the hash-chained audit log; the schema comes from the core package's host-run DatabaseMigrator. Platform-independent alternative to SQL Server.

Feedemy.KeyManagement.Providers.Sqlite

SQLite persistence provider for Feedemy.KeyManagement. Provides lightweight, file-based storage for key metadata, versions, and audit logs. Ideal for development, testing, and single-server deployments.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.0.0 54 11/24/2026
3.5.0 283 10/11/2026
3.4.0 240 9/6/2026
3.3.1 507 8/27/2026
3.3.0 594 6/11/2026
3.2.1 247 4/24/2026
3.2.0 167 4/24/2026
3.1.0 223 3/9/2026
3.0.6 170 3/9/2026
3.0.5 175 3/9/2026
3.0.4 169 3/9/2026
3.0.3 172 3/9/2026
3.0.2 176 3/9/2026
3.0.1 171 2/27/2026
2.5.10 338 1/21/2026
2.5.9 212 1/10/2026
2.5.8 173 1/10/2026
2.5.7 158 1/9/2026
2.5.6 158 1/9/2026
2.5.5 188 1/6/2026
Loading failed

v4.0.0 - Admin and read API surface (clean break)
Operations views: rotation history, rotation postponement, blocked rotations, outstanding endorsements, ceremony history, expiring certificates, the alarm pass (IKeyAlarmHandler, ListAlarmsAsync) and fleet gauges; schema V2.3.0.

Breaking, with a one-way schema upgrade (V2.0.0). Mixed 3.x/4.0 fleets
are unsupported; going back is a database restore. Coming from 3.5.x
(3.6.0 and 3.7.0 were not published), in this order:
1. Stop every 3.x node.
2. Back up the database.
3. Remove Enlist=false from the KeyManagement connection string: the
  SQL Server and PostgreSQL registrations refuse it.
4. The first 4.0 node to start migrates the schema itself (no host
  call; SchemaMigrationMode.Validate keeps it to a version check for
  DBA-run migrations), after copying the 3.5 tables into a backup
  schema that IKeyManagementRestore.RestoreBackupAsync restores (key
  storage put back into the format 3.5.x reads first). A failed
  migration stops the start and changes nothing. It refuses rows 4.0
  could not write back (filled 3.x-unused audit columns, tags or custom
  metadata out of the label rules); docs/MIGRATION_GUIDE.md has the SQL
  to fix them.
5. With fallback storage, delete each node's fallback *.key files: up to
  3.6.x the listener wrote decrypted key material there.
6. Start the 4.0 nodes; the fallback startup sync refills the store at
  every start - check its log line.
7. A backup tool that decrypts without the database moves to the opt-in
  IKeyMaterialRecovery (WithRecoveryReads, key initialization off).
See CHANGELOG.md ([4.0.0] Upgrade) and docs/MIGRATION_GUIDE.md (3.x -> 4.0
member mapping).

- The 3.x read and command interfaces are replaced by six, split by plane:
 IKeyMaterialService (data plane, MaterialLookup), IKeyCatalog,
 IKeyEndorsementCatalog and IKeyAuditLog (typed read models, keyset paging
 with Page<T> and PageRequest), IKeyAdministration and
 IKeyEndorsementCommands (commands); and the opt-in disaster-recovery
 read IKeyMaterialRecovery.
- Every command returns CommandResult<T>: Status (Succeeded, Unchanged,
 AwaitingEndorsement, Validated, Failed), a typed KeyError with category
 and retry advice, typed warnings, AuditId, TraceId and Replayed. Every
 command takes CommandOptions: Actor, Reason (required on state
 transitions), IfMatch (the key's ETag), a persisted IdempotencyKey and
 ValidateOnly.
- A typed Actor; optional host hooks IActorAccessor and
 IKeyManagementAuthorizer (default: allow all).
- Audit is fail-closed and hash-chained: rows are written in the change's
 transaction (AUDIT_UNAVAILABLE otherwise); IKeyAuditLog verifies the
 chain and exports its head.
- Key and version lifecycle states with reasons, labels instead of tags,
 informational key expiry, one rotation standing for the due list, health
 and endorsement states.
- Settings change through seven Set* commands. Wrapped material import
 (CreateImportJobAsync, KeyMaterialSource.Wrapped, KeyMaterialWrapping).
 Persisted endorsement request ledger with cancellation and batch import.
- Key storage is never written over: the master key bootstrap and key
 definition files adopt material key storage already holds, a caller's
 creation into such a slot is KEY_NAME_CONFLICT, and a new version skips
 version numbers key storage already holds.
- New options: AllowPlaintextImport, LogMaterialAccess,
 IdempotencyRetention, Endorsement.RequestLifetime, EnableRecoveryReads,
 SchemaMigration (WithSchemaMigration).
- The library migrates its schema at startup (a backup schema before a
 major migration, DatabaseMigrator.ListBackupsAsync and
 IKeyManagementRestore.RestoreBackupAsync)
 and refuses a schema newer than the package.
 MetricsIncludeKeyName now defaults to false.
- Removed: the 15 obsolete Use* builder methods, the 3.x result, request
 and report types, the generic cache GetAsync/SetAsync, four unused
 cache TTL options, EnableFallbackSync (the fallback startup sync runs
 whenever fallback storage is configured) and three inert fallback
 options. The storage coordinator's write result is renamed
 StorageWriteResult.

Earlier releases (full notes: CHANGELOG.md in the repository)

v3.7.0 (not published to NuGet) - Admin API correctness: reads throw on
failure, every privileged write is audited, commands answer typed error
codes, the master key is protected, retention applies on every new
version. No schema migration.

v3.6.0 (not published to NuGet) - Offline-root key endorsement, phase 2:
the rotation gate (EndorsementPolicy.Required). No schema migration.

v3.5.0 - Offline-root key endorsement, phase 1 ("sign only"). Schema
migration V1.4.0 (additive).

v3.3.1 and earlier - dependency maintenance, storage hardening, write
atomicity, cache coordination, the 3.0.0 security and performance release.