Tooark.Securities
4.9.0
See the version list below for details.
dotnet add package Tooark.Securities --version 4.9.0
NuGet\Install-Package Tooark.Securities -Version 4.9.0
<PackageReference Include="Tooark.Securities" Version="4.9.0" />
<PackageVersion Include="Tooark.Securities" Version="4.9.0" />
<PackageReference Include="Tooark.Securities" />
paket add Tooark.Securities --version 4.9.0
#r "nuget: Tooark.Securities, 4.9.0"
#:package Tooark.Securities@4.9.0
#addin nuget:?package=Tooark.Securities&version=4.9.0
#tool nuget:?package=Tooark.Securities&version=4.9.0
Tooark.Securities
Security library for .NET applications, providing AES cryptography (single key or multiple keys with rotation), JWT issuing, validation and Bearer authentication with support for multiple algorithms, password hashing (PBKDF2), secure tokens, TOTP second factor with recovery codes, plus the configuration of ASP.NET Core Data Protection.
π Docs: Tooark.Securities on the site Β· All packages Β· API reference
π Languages: πΊπΈ English (this file) Β· π§π· PortuguΓͺs
π Contents
- Package Contents
- Installation
- Configuration
- JWT - Supported Algorithms
- JWT - Bearer Authentication
- Cryptography - Supported Algorithms
- Cryptography - Multiple Keys and Rotation
- Data Protection - Key Ring
- Password Hashing
- Secure Tokens, TOTP and Recovery Codes
- Usage Examples
- Generating Keys
- Dependencies
- Best Practices
- Error Codes and Solutions
- Contributing
- Help & Security
- Support
- License
π¦ Package Contents
Services
| Class | Description |
|---|---|
JwtTokenService |
Service for creating and validating JWT tokens |
CryptographyService |
AES-256 encryption/decryption service with a single key |
KeyedCryptographyService |
AES-256 with multiple identified keys and rotation; also serves the single-key contract |
PasswordHashService |
Password hashing with PBKDF2-HMAC-SHA256 in the PHC format |
Interfaces
| Interface | Description |
|---|---|
IJwtTokenService |
Contract for handling JWT tokens |
ICryptographyService |
Contract for AES encryption/decryption |
IKeyedCryptographyService |
ICryptographyService plus key identification, rotation and re-encryption |
IPasswordHashService |
Contract for hashing and verifying passwords |
| Member | Description |
|---|---|
IJwtTokenService.Create |
Creates the token. Synchronous: the handler exposes no async creation |
IJwtTokenService.ValidateAsync |
Validates the token. Direct path to the handler, which is asynchronous |
IJwtTokenService.Validate |
Validates the token. Synchronous wrapper of ValidateAsync |
ICryptographyService.Encrypt |
Encrypts. Synchronous: in-memory AES, no I/O |
ICryptographyService.Decrypt |
Decrypts. Synchronous, for the same reason |
IKeyedCryptographyService.CurrentKeyId |
Identifier of the key that encrypts new values |
IKeyedCryptographyService.KeyIds |
Identifiers of every configured key |
IKeyedCryptographyService.Encrypt(text, keyId) |
Encrypts with a specific key |
IKeyedCryptographyService.KeyIdOf |
Reads the key identifier of a value; null for a legacy value without prefix |
IKeyedCryptographyService.IsCurrent |
Whether the value was encrypted with the current key |
IKeyedCryptographyService.ReEncrypt |
Decrypts with the key that wrote the value and encrypts with the current one |
IPasswordHashService.Hash |
Hashes a password with a random salt |
IPasswordHashService.Verify |
Checks a password against a stored hash, in constant time; never throws |
IPasswordHashService.NeedsRehash |
Whether the hash uses parameters older than the current options |
Static classes
| Class | Description |
|---|---|
SecureToken |
Random tokens (password reset, e-mail confirmation, API key): Create, Hash and Verify |
Totp |
Time-based one-time passwords (RFC 6238): secret, otpauth:// URI, Compute and Verify with replay protection |
RecoveryCodes |
Second-factor recovery codes: Generate and Normalize, stored as SecureToken hashes |
TooarkClaimNames |
Names of the claims the token service emits and reads (id, login, security, sub, preferred_username) |
DTOs
| Class | Description |
|---|---|
JwtTokenDto |
Data for creating a token (id, login, security) |
UserTokenDto |
Result of the token validation, with the claims |
Options
| Class | Description |
|---|---|
JwtOptions |
JWT settings (algorithm, keys, issuer(s), audience(s), expiration, claim names) |
CryptographyOptions |
Cryptography settings (algorithm, secret or secretBase64, identified keys) |
PasswordHashOptions |
Password hashing settings (iterations, salt size, hash size) |
KeyRingOptions |
Data Protection key ring (application, storage, certificate, rotation) |
Extensions
| Class | Description |
|---|---|
RoleClaimsExtension |
Extension that converts JwtTokenDto into claims, with the legacy names, the standard names or both |
π§ Installation
dotnet add package Tooark.Securities
βοΈ Configuration
appsettings.json
To configure the security services, add the Jwt, Cryptography, PasswordHash and DataProtection sections to your appsettings.json. Only the sections of the services you use are needed, and PasswordHash is optional even then (safe defaults):
Example configuration for a JWT token with symmetric algorithms (uses Secret for signing and validation):
{
"Jwt": {
"Algorithm": "HS256",
"Secret": "your-secret-key-with-at-least-32-characters",
"Issuer": "your-application",
"Audience": "your-clients",
"ExpirationTime": 60
}
}
Example configuration for a JWT token with asymmetric algorithms (PrivateKey required for signing, PublicKey required for validation):
{
"Jwt": {
"Algorithm": "RS256",
"PrivateKey": "your-private-key-in-base64",
"PublicKey": "your-public-key-in-base64",
"Issuer": "your-application",
"Audience": "your-clients",
"ExpirationTime": 60
}
}
Example configuration for AES cryptography, with the 32-byte AES key in Base64 (generate it with
openssl rand -base64 32; the key is used directly, without derivation):
{
"Cryptography": {
"Algorithm": "GCM",
"SecretBase64": "32-byte-key-in-base64"
}
}
Or with several identified keys, to rotate the key without re-encrypting everything at once (see
Cryptography - Multiple Keys and Rotation). SecretBase64 stays
only while there are values written before the keys were adopted:
{
"Cryptography": {
"Algorithm": "GCM",
"CurrentKeyId": "k2",
"Keys": {
"k1": "old-32-byte-key-in-base64",
"k2": "new-32-byte-key-in-base64"
},
"SecretBase64": "legacy-32-byte-key-in-base64"
}
}
Example configuration for password hashing (every key is optional β these are the defaults):
{
"PasswordHash": {
"Iterations": 600000,
"SaltSize": 16,
"HashSize": 32
}
}
JwtOptions properties
| Property | Type | Default | Description |
|---|---|---|---|
Algorithm |
string | ES256 |
Signing algorithm. Unknown values throw |
Secret |
string? | null |
Key for symmetric algorithms (HS256/384/512) |
PrivateKey |
string? | null |
Base64 private key (PKCS#8) for signing |
PublicKey |
string? | null |
Base64 public key (SPKI) for validation |
Issuer |
string? | null |
Issuer accepted on validation and written to the token |
Issuers |
string[]? | null |
Additional issuers accepted on validation |
Audience |
string? | null |
Audience accepted on validation and written to the token |
Audiences |
string[]? | null |
Additional audiences accepted on validation |
ExpirationTime |
int | 5 |
Token expiration in minutes |
EmitLegacyClaims |
bool | true |
Emits the id and login claims (Tooark names) |
EmitStandardClaims |
bool | false |
Emits the sub and preferred_username claims (JWT/OpenID Connect names) |
Issuer/IssuersandAudience/Audiencesadd up: providing any of them turns on the validation of that field. When none is provided, the validation of that field is turned off. Theaudienceparameter ofCreateandValidate/ValidateAsynctakes precedence over the configuration.
PrivateKeyandPublicKeyaccept both the raw Base64 and the full PEM: the-----BEGIN/END ... KEY-----delimiters and the line breaks are removed on assignment.β οΈ Changes in v5: the claim defaults invert β
EmitStandardClaimsbecomestrueandEmitLegacyClaimsbecomesfalse. Set both flags explicitly today so the upgrade does not change your tokens. At least one of them must be on; both off fail at startup (Options.Jwt.ClaimsNotConfigured). See Claim names.
Example with multiple issuers and audiences:
{
"Jwt": {
"Algorithm": "ES256",
"PublicKey": "your-public-key-in-base64",
"Issuers": ["legacy-api", "new-api"],
"Audiences": ["web-app", "mobile-app"],
"ExpirationTime": 60
}
}
CryptographyOptions properties
| Property | Type | Default | Description |
|---|---|---|---|
Algorithm |
string | GCM |
AES-256 mode: GCM, CBC or CBCUnsafe (decrypt only) |
Secret |
string? | null |
Obsolete, removed in v5. Key derived via SHA256 |
SecretBase64 |
string? | null |
32-byte AES key used directly |
CurrentKeyId |
string? | null |
Identifier of the key in Keys that encrypts new values |
Keys |
Dictionary<string, string> |
empty | Identified 32-byte AES keys in Base64, for rotation |
Without
Keys,SecretBase64(or the obsoleteSecret) is required. When both are provided,SecretBase64takes precedence.SecretBase64must represent exactly 32 bytes (AES-256) β invalid values fail at startup. Generate a key withConvert.ToBase64String(RandomNumberGenerator.GetBytes(32)).With
Keys,CurrentKeyIdis required and must be one of the identifiers; each identifier uses only letters, digits, hyphen and underscore (never a dot), and each key is exactly 32 bytes in Base64 β anything else fails at startup.Secret/SecretBase64become the legacy key: they only open values written without a key prefix, and can be removed once none is left.β οΈ Changes in v5: the text
Secretis obsolete since v4.8.0 and is removed in v5. The key it derives is the SHA-256 of the text: put that value inSecretBase64and everything already encrypted keeps opening, with no re-encryption, including the legacy values read withCBCUnsafe:Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(secret))).[Obsolete]only warns code that assignsSecret; setting it inappsettings.jsonraises no compiler warning.β οΈ Changes in v5: an unknown
Algorithm(a typo such asGMC) fails at startup. On the 4.x line it silently falls back toGCM. Missing or empty still meansGCM.
PasswordHashOptions properties
| Property | Type | Default | Description |
|---|---|---|---|
Iterations |
int | 600000 |
PBKDF2 iterations (OWASP recommendation). Minimum 100.000 |
SaltSize |
int | 16 |
Salt size in bytes. Minimum 16 |
HashSize |
int | 32 |
Derived hash size in bytes. Minimum 32 |
Values below the minimums fail at startup: a weak configuration is a configuration error, never silently replaced. Raising a value does not break stored hashes β they keep validating and
NeedsRehashtells the login flow to rewrite them.
Example configuration for Data Protection (every key is optional β see Data Protection - Key Ring):
{
"DataProtection": {
"ApplicationName": "my-application",
"RequirePersistentKeyStorage": true,
"KeysPath": "/var/dataprotection/keys",
"CertificatePath": "/var/dataprotection/certificate.pfx",
"CertificatePassword": "certificate-password"
}
}
KeyRingOptions properties
| Property | Type | Default | Description |
|---|---|---|---|
ApplicationName |
string? | null |
Name that isolates the key ring. Same name and same storage share the keys |
KeysPath |
string? | null |
Key directory. Null keeps the ASP.NET Core default location |
KeyLifetimeDays |
int? | null |
Lifetime of each key in days (minimum 7). Null keeps the ASP.NET Core 90 days |
DisableAutomaticKeyGeneration |
bool | false |
Only reads the keys, never creates new ones (another app rotates the key ring) |
RequirePersistentKeyStorage |
bool? | null |
With true, the app does not start without a key storage. Null keeps it off |
CertificatePath |
string? | null |
RSA .pfx certificate, with private key, that protects the keys at rest |
CertificatePassword |
string? | null |
Password of the CertificatePath certificate |
CertificateThumbprint |
string? | null |
Certificate from the My store (user or machine), instead of CertificatePath |
ReadKeys |
Func<IServiceProvider, Task<IEnumerable<string>>>? |
null |
Reads the XML of every key from the custom storage. Code only |
WriteKey |
Func<IServiceProvider, string, string, Task>? |
null |
Writes a new key (name and XML) to the custom storage. Code only |
ConfigureDataProtection |
Action<IDataProtectionBuilder>? |
null |
Callback with the native builder, run last. Code only |
No key is required: whatever is not provided follows the ASP.NET Core default. Validation only stops, at startup, what would fail later: a lifetime below 7 days,
CertificatePathtogether withCertificateThumbprint,CertificatePasswordwithoutCertificatePath, a certificate that is missing, unreadable, without a private key or without an RSA key, only one of theReadKeysandWriteKeycallbacks, and the callbacks together withKeysPath. The key storage lock (RequirePersistentKeyStorage) is opt-in: see Clusters, containers and autoscaling.
Program.cs
using Tooark.Securities.Injections;
var builder = WebApplication.CreateBuilder(args);
// Adds the security services
builder.Services.AddTooarkSecurities(builder.Configuration);
var app = builder.Build();
Or, to add only the JWT token service:
using Tooark.Securities.Injections;
var builder = WebApplication.CreateBuilder(args);
// Adds the security services
builder.Services.AddTooarkJwtToken(builder.Configuration);
var app = builder.Build();
Or, to add only the cryptography service:
using Tooark.Securities.Injections;
var builder = WebApplication.CreateBuilder(args);
// Adds the security services
builder.Services.AddTooarkCryptography(builder.Configuration);
var app = builder.Build();
Or, to add only Data Protection:
using Tooark.Securities.Injections;
var builder = WebApplication.CreateBuilder(args);
// Adds Data Protection with the key ring from the DataProtection section
builder.Services.AddTooarkDataProtection(builder.Configuration);
var app = builder.Build();
Or, to add only the password hashing service (AddTooarkSecurities already registers it, with or without the
PasswordHash section):
using Tooark.Securities.Injections;
var builder = WebApplication.CreateBuilder(args);
// Adds the password hashing service; the configuration and the callback are optional
builder.Services.AddTooarkPasswordHash(builder.Configuration, options => options.Iterations = 800_000);
var app = builder.Build();
To authenticate the requests of an API with the tokens the service itself issues, register the Bearer scheme
from the same Jwt section (see JWT - Bearer Authentication):
using Tooark.Securities.Injections;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTooarkJwtToken(builder.Configuration); // issues the tokens
builder.Services.AddTooarkJwtBearer(builder.Configuration); // validates them on every request
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
SecureToken,TotpandRecoveryCodesare static classes: nothing to register.
π JWT - Supported Algorithms
Symmetric Algorithms (HMAC)
| Algorithm | Description | Requirements |
|---|---|---|
HS256 |
HMAC-SHA256 | Secret (β₯32 bytes) |
HS384 |
HMAC-SHA384 | Secret (β₯48 bytes) |
HS512 |
HMAC-SHA512 | Secret (β₯64 bytes) |
The minimums follow RFC 7518 (HMAC key at least as long as the hash output) and are validated at startup (
Options.Jwt.SecretTooShort). The size is measured in bytes (UTF-8): non-ASCII characters take more than one byte.
Asymmetric Algorithms (RSA)
| Algorithm | Description | Requirements |
|---|---|---|
RS256 |
RSA-SHA256 | PrivateKey/PublicKey (β₯2048 bits) |
RS384 |
RSA-SHA384 | PrivateKey/PublicKey (β₯2048 bits) |
RS512 |
RSA-SHA512 | PrivateKey/PublicKey (β₯2048 bits) |
PS256 |
RSA-PSS-SHA256 | PrivateKey/PublicKey (β₯2048 bits) |
PS384 |
RSA-PSS-SHA384 | PrivateKey/PublicKey (β₯2048 bits) |
PS512 |
RSA-PSS-SHA512 | PrivateKey/PublicKey (β₯2048 bits) |
Asymmetric Algorithms (ECDsa)
| Algorithm | Description | Required Curve |
|---|---|---|
ES256 |
ECDSA-SHA256 | P-256 (secp256r1) |
ES384 |
ECDSA-SHA384 | P-384 (secp384r1) |
ES512 |
ECDSA-SHA512 | P-521 (secp521r1) |
The default algorithm is
ES256whenAlgorithmis not provided. Unknown values throw (Options.Jwt.AlgorithmNotSupported) β in security configuration, an invalid algorithm is never silently replaced by another. Internally, creation and validation use theJsonWebTokenHandler(the current Microsoft.IdentityModel handler);UserTokenDtoaccepts bothJsonWebTokenand the legacyJwtSecurityToken.
πͺͺ JWT - Bearer Authentication
AddTooarkJwtBearer registers the ASP.NET Core Bearer authentication scheme for the tokens that
JwtTokenService issues. It reads the same Jwt section and builds the handler's TokenValidationParameters
with the same rules as Validate: same algorithm and key (HMAC secret or public key), issuer(s), audience(s),
required expiration and signature, zero clock skew. A token accepted by one is accepted by the other, and
nobody repeats the key, issuer and audience in a hand-written AddJwtBearer.
builder.Services.AddTooarkJwtToken(builder.Configuration);
builder.Services.AddTooarkJwtBearer(builder.Configuration, bearer =>
{
// Optional: the native options, applied last
bearer.Challenge = "Bearer realm=\"orders-api\"";
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/me", (ClaimsPrincipal user) => new
{
Id = user.FindFirstValue(TooarkClaimNames.Id),
Login = user.FindFirstValue(TooarkClaimNames.Login)
}).RequireAuthorization();
What the registration sets:
- Scheme
Bearer(JwtBearerDefaults.AuthenticationScheme) as the default authentication scheme, unless the application already defined one β the first registered scheme wins, as inTooark.Securities.OpenId. MapInboundClaims = false: the claims reach theClaimsPrincipalwith the names written in the token (id,sub,login), not with theClaimTypesURIs. Read them with theTooarkClaimNamesconstants.- Fail fast: the key is loaded and validated at registration. Without a validation key (asymmetric algorithm
with
PrivateKeyonly) the startup fails withOptions.Jwt.KeyNotConfigured;PublicKey. - The
configurecallback receives the nativeJwtBearerOptionsand runs last, so anything can be adjusted, including the Tooark defaults.
The application still needs app.UseAuthentication() and app.UseAuthorization(). A resource server that only
validates tokens (no issuing) configures the Jwt section with the PublicKey only and calls
AddTooarkJwtBearer alone.
Claim names
JwtTokenService writes the user data as claims. Two naming sets exist, chosen by JwtOptions:
| Data | Legacy name (EmitLegacyClaims) |
Standard name (EmitStandardClaims) |
Standard |
|---|---|---|---|
Id |
id |
sub |
RFC 7519 |
Login |
login |
preferred_username |
OpenID Connect Core |
Security |
security |
security (no standard equivalent) |
β |
- In the 4.x line, the default emits the legacy names only (
EmitLegacyClaims = true,EmitStandardClaims = false), so existing consumers see no change. - With both flags on, the token carries both sets: the migration path. New consumers read
subwhile the old ones still readid. UserTokenDtoreadsidand falls back tosub,loginand falls back topreferred_username, so a token issued in any mode is read.- The constants live in
TooarkClaimNames;RoleClaimsExtension.GetClaimshas overloads taking the flags or theJwtOptions. The parameterless overload, which hard-codes the legacy names, is obsolete since v4.8.0 and removed in v5: useGetClaims(options).
β οΈ Changes in v5: the defaults invert β
EmitStandardClaims = trueandEmitLegacyClaims = false. A token issued by a v5 service without explicit flags hassuband noid. Set the two flags explicitly in theJwtsection today, and move the readers tosub/preferred_username(or toUserTokenDto, which handles both), so the upgrade changes nothing.
Testing emission and expiration
JwtTokenService has a constructor that takes a TimeProvider: iat, nbf and exp come from it, and the
lifetime validation uses it too. A fake clock tests the expiration without waiting:
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 1, 15, 10, 0, 0, TimeSpan.Zero));
var service = new JwtTokenService(Options.Create(jwtOptions), clock);
var token = service.Create(new JwtTokenDto(userId, login, securityStamp));
clock.Advance(TimeSpan.FromMinutes(jwtOptions.ExpirationTime + 1));
var result = service.Validate(token); // result.ErrorToken == "Token.Expired"
When the container registers a TimeProvider, dependency injection picks that constructor; otherwise the
service uses TimeProvider.System, with the handler's own lifetime validation.
π Cryptography - Supported Algorithms
| Algorithm | Mode | Description |
|---|---|---|
GCM |
AES-256-GCM | Recommended - Authenticated encryption |
CBC |
AES-256-CBC | Traditional mode with random IV |
CBCUnsafe |
AES-256-CBC | β οΈ Legacy - zero IV, decryption only |
CBCUnsafeexists only to read old data encrypted with a zero IV: encrypting in this mode throws (Options.Cryptography.AlgorithmDecryptOnly). For new data, useGCM. The mode stays in v5, for decryption only.
π Cryptography - Multiple Keys and Rotation
With a single key, rotating it means decrypting everything with the old key and encrypting with the new one, by
hand and all at once. IKeyedCryptographyService keeps several identified keys: new values go out with the
current key, old values keep opening with the key that wrote them, and each record is re-encrypted when it is
convenient β on read, in a batch job, or never.
Configuring the keys
{
"Cryptography": {
"Algorithm": "GCM",
"CurrentKeyId": "k2",
"Keys": {
"k1": "<Base64 of the old 32-byte key>",
"k2": "<Base64 of the new 32-byte key>"
},
"SecretBase64": "<Base64 of the single key used before, if there are values written with it>"
}
}
When Keys is filled, AddTooarkCryptography (and AddTooarkSecurities) registers KeyedCryptographyService as
both ICryptographyService and IKeyedCryptographyService: the code that already injects
ICryptographyService starts encrypting with the current key and reading legacy values with no change. Without
Keys, the single-key CryptographyService is registered as always. The identified keys are validated at
startup (see the CryptographyOptions properties).
Value format
tk1.k2.AbCd... identified value: format version . key id . Base64 payload
AbCd... legacy value, written before the keys were adopted
The dot does not exist in the Base64 alphabet, so a legacy value is never mistaken for an identified one. The
payload is exactly what CryptographyService produces with that key and the configured algorithm.
Rotation flow
- Generate the new key (
openssl rand -base64 32), add it toKeysunder a new identifier and pointCurrentKeyIdto it. Keep the old key inKeys. - Deploy. New values go out with the new key; old values keep opening.
- Re-encrypt the stored values at your own pace β on read, as below, or in a batch job.
- When no value uses the old key anymore (
KeyIdOfreturns the old identifier, ornullfor legacy values), remove it fromKeysβ andSecretBase64/Secretonce no legacy value is left.
public class CustomerRepository(IKeyedCryptographyService crypto, AppDbContext db)
{
public async Task<string> ReadDocumentAsync(Customer customer)
{
var document = crypto.Decrypt(customer.EncryptedDocument);
// Re-encrypt on read: the record moves to the current key the first time it is used
if (!crypto.IsCurrent(customer.EncryptedDocument))
{
customer.EncryptedDocument = crypto.ReEncrypt(customer.EncryptedDocument);
await db.SaveChangesAsync();
}
return document;
}
}
Limitations
- Removing a key makes its values unreadable:
Decryptfails withCryptography.KeyNotFound;{id}. Only remove a key after re-encrypting everything written with it. - Legacy values need the legacy key: without
Secret/SecretBase64, a value without prefix fails withCryptography.LegacyKeyNotConfigured. - One algorithm for all keys:
Algorithmapplies to every key, including the legacy one. Changing the algorithm is a re-encryption, not a rotation. ReEncryptreturns the same text when the value is already on the current key.- The value grows by the prefix (
tk1.plus the identifier and a dot): size the database column accordingly.
π Data Protection - Key Ring
ASP.NET Core Data Protection protects the short-lived payloads of the application β authentication cookie,
OpenID Connect correlation cookies and state, antiforgery, TempData β without anyone configuring it. The
default, however, writes the keys to the local disk of each instance: with more than one instance, or in a
container that restarts without a volume, one instance cannot open what another protected (Correlation failed,
Unable to unprotect the message.State, users signed out). AddTooarkDataProtection configures where the key
ring lives, how the keys are protected and which application it isolates.
The feature is optional and does not replace ICryptographyService:
| Feature | Use for | Key |
|---|---|---|
ICryptographyService |
Data stored indefinitely (database columns) | Fixed, under the application's control |
| Data Protection | Short-lived payloads (cookies, link tokens) | Rotates on its own, every 90 days by default |
Do not use Data Protection for long-lived data at rest: if the key ring is lost, everything it protected becomes unreadable.
Storage and protection beyond the options
The options cover what Data Protection offers without an extra package: directory, certificate and
custom storage through callbacks. For Redis,
Azure Blob Storage, a database or Azure Key Vault, install the provider package and use
ConfigureDataProtection, which receives the native builder and runs last:
builder.Services.AddTooarkDataProtection(builder.Configuration, options =>
{
options.ConfigureDataProtection = dataProtection => dataProtection
.PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
});
For the application database with Entity Framework Core, the official package
Microsoft.AspNetCore.DataProtection.EntityFrameworkCore does the same through the DbContext: the context
implements IDataProtectionKeyContext (a DbSet<DataProtectionKey>) and the builder persists the keys to it.
Tooark.Securities adds no Entity Framework Core dependency for that β only the application that chooses this
storage installs the package:
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options), IDataProtectionKeyContext
{
public DbSet<DataProtectionKey> DataProtectionKeys => Set<DataProtectionKey>();
}
builder.Services.AddTooarkDataProtection(builder.Configuration, options =>
{
options.ConfigureDataProtection = dataProtection => dataProtection
.PersistKeysToDbContext<AppDbContext>();
});
Nothing is locked: services.AddDataProtection() is still available before or after, and whatever is registered
last wins.
Custom storage with ReadKeys and WriteKey
To keep the keys in a database, a storage or a vault without installing a provider package, provide two
functions: ReadKeys, which returns the XML of every key, and WriteKey, which writes a new key. They replace
KeysPath (setting both fails at startup) and satisfy the RequirePersistentKeyStorage lock.
- Each call receives the service provider of its own scope: scoped services, such as a
DbContext, are resolved directly. WriteKeyreceives the key name (key-{guid}, unique) and the XML. With a certificate configured, the XML arrives already encrypted, and the storage never sees the key in the clear.- ASP.NET Core calls the storage synchronously, and Tooark waits for the task. Calls are rare: reads when the key ring loads (at startup and every 24 hours) and after a key is created; writes on the first run and on every rotation (90 days by default).
- An exception in the callbacks reaches whoever uses Data Protection. Let it propagate: handling the failure and returning an empty list makes ASP.NET Core create new keys (see the table below).
- The callbacks exist in code only, like
ConfigureDataProtection.
β Do: a table in the application database
{
"ConnectionStrings": {
"Default": "Server=...;Database=my-api;..."
},
"DataProtection": {
"ApplicationName": "my-api",
"RequirePersistentKeyStorage": true,
"CertificatePath": "/run/secrets/dataprotection.pfx"
}
}
using Microsoft.EntityFrameworkCore;
using Tooark.Securities.Injections;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
builder.Services.AddTooarkDataProtection(builder.Configuration, options =>
{
// Every key, expired ones included: they still open what they protected
options.ReadKeys = async services =>
{
var db = services.GetRequiredService<AppDbContext>();
return await db.DataProtectionKeys.Select(key => key.Xml).ToListAsync();
};
// Insert only: each key has a unique name and is never changed or deleted
options.WriteKey = async (services, name, xml) =>
{
var db = services.GetRequiredService<AppDbContext>();
db.DataProtectionKeys.Add(new DataProtectionKeyRecord { Name = name, Xml = xml });
await db.SaveChangesAsync();
};
});
var app = builder.Build();
app.Run();
The table is a regular entity of the application DbContext, created by a migration before the first startup:
public class DataProtectionKeyRecord
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Xml { get; set; } = string.Empty;
}
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<DataProtectionKeyRecord> DataProtectionKeys => Set<DataProtectionKeyRecord>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Unique name: a second write with the same name fails instead of overwriting the key
modelBuilder.Entity<DataProtectionKeyRecord>().HasIndex(key => key.Name).IsUnique();
}
}
The outcome: every instance reads the same keys, a recreated pod still opens the old tokens, and each rotation
adds a row to the table, keeping the previous ones. The certificate password comes from outside
appsettings.json, through the DataProtection__CertificatePassword environment variable.
β Don't: callbacks that lose keys
β οΈ These callbacks lose data, and the lock does not notice: as far as it knows, a storage is configured.
// β In-memory list: each instance has its own, and it is gone on every restart
var keys = new List<string>();
builder.Services.AddTooarkDataProtection(builder.Configuration, options =>
{
options.ReadKeys = _ => Task.FromResult<IEnumerable<string>>(keys);
options.WriteKey = (_, _, xml) =>
{
keys.Add(xml);
return Task.CompletedTask;
};
});
// β A single row, overwritten on every new key: the previous key disappears
options.ReadKeys = async services =>
{
var db = services.GetRequiredService<AppDbContext>();
var current = await db.DataProtectionKeys.SingleOrDefaultAsync();
return current is null ? [] : [current.Xml];
};
options.WriteKey = async (services, name, xml) =>
{
var db = services.GetRequiredService<AppDbContext>();
var current = await db.DataProtectionKeys.SingleOrDefaultAsync();
if (current is null)
{
db.DataProtectionKeys.Add(new DataProtectionKeyRecord { Name = name, Xml = xml });
}
else
{
current.Name = name;
current.Xml = xml;
}
await db.SaveChangesAsync();
};
| Mistake | What happens |
|---|---|
Keeping the keys in memory (list, IMemoryCache, static field) |
Each instance has its own keys, and they are gone on restart: The key {β¦} was not found in the key ring on the other instance and after every deploy. It is the same as configuring no storage |
| Overwriting the key instead of inserting | It works until the first rotation (90 days by default) and passes any short test. On rotation the previous key disappears: seconds later, when the key ring reloads, everything it protected stops opening, from sessions and tokens to stored data |
| Reading only the latest key, or filtering out expired ones | The same effect as the previous row, even with the table intact |
| Deleting old keys (cleanup routine, TTL, cache with expiration) | What they protected becomes unreadable. For data at rest, the loss is permanent |
| Handling the read failure and returning an empty list | With no keys, ASP.NET Core creates and writes new keys, and what was protected before does not open on that instance. Let the exception propagate |
Clusters, containers and autoscaling
With no storage configured, ASP.NET Core writes the keys to the user profile, which in a container lives inside the instance itself. The application starts normally and only logs a warning. The problem shows up when the pod is recreated or a second instance joins: users signed out, OpenID Connect sign-in failing and, for whatever was protected at rest, unreadable data.
RequirePersistentKeyStorage turns that warning into a startup failure. With true, the application does not
start without a key storage (Options.DataProtection.KeyStorageNotConfigured): KeysPath, the ReadKeys and
WriteKey callbacks, a PersistKeysTo* in ConfigureDataProtection or one chained to services.AddDataProtection(), before or after
AddTooarkDataProtection. The check runs when the host starts and, without a host, on the first use of Data
Protection.
The lock is off by default in this version, so applications already on v4.3.0 keep their behavior.
β οΈ Changes in v5: with no value set, the lock turns on when the application runs in a container (
DOTNET_RUNNING_IN_CONTAINER, which the official .NET images define, orKUBERNETES_SERVICE_HOST). An API that uses no cookies (JWT only) does not depend on persistent keys: setfalseto keep it off after that change too.
β Don't: keys tied to the instance
{
"DataProtection": {
"ApplicationName": "my-api"
}
}
using Tooark.Securities.Injections;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTooarkDataProtection(builder.Configuration);
var app = builder.Build();
app.Run();
β οΈ This configuration loses data. With no
KeysPathand no external storage, each container creates its own key in~/.aspnet/DataProtection-Keys, inside itself. Nothing fails on registration or at startup: the log only warnsStoring keys in a directory 'β¦' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
| When | What happens |
|---|---|
| The request reaches another instance | The other instance does not have the key: The key {β¦} was not found in the key ring. The session cookie is discarded and the user goes back to sign-in, OpenID Connect sign-in fails with Correlation failed or Unable to unprotect the message.State, and antiforgery forms are rejected |
| Deploy, restart, recreated pod or autoscaling down | The key goes away with the container, and every session drops at once |
| A protected value was stored in the database | Lost for good: no new instance has the key, and there is no way to recover it |
With "RequirePersistentKeyStorage": true, this same configuration does not start: the error shows up on deploy, not
later, with users already signed in.
β Don't: KeysPath without a shared volume
{
"DataProtection": {
"ApplicationName": "my-api",
"RequirePersistentKeyStorage": true,
"KeysPath": "/var/dataprotection/keys"
}
}
β οΈ The lock passes and the data is lost just the same. The directory exists, but without a mounted volume it sits in each container's writable layer: the outcome is the one from the previous example. The same goes for a volume that only one pod mounts, such as a per-replica StatefulSet volume or a
ReadWriteOncedisk. The lock checks that a storage exists, not that it outlives the instance.
β Do: a shared, protected key ring
{
"DataProtection": {
"ApplicationName": "my-api",
"RequirePersistentKeyStorage": true,
"KeysPath": "/var/dataprotection/keys",
"CertificatePath": "/run/secrets/dataprotection.pfx"
}
}
using Tooark.Securities.Injections;
var builder = WebApplication.CreateBuilder(args);
// Shared key ring: same ApplicationName, same directory and same certificate on every instance
builder.Services.AddTooarkDataProtection(builder.Configuration);
var app = builder.Build();
app.Run();
/var/dataprotection/keysis a volume shared by every instance: NFS, Azure Files or EFS, and in Kubernetes aPersistentVolumeClaimwithReadWriteMany./run/secrets/dataprotection.pfxis the certificate mounted as a secret, and the password comes from outsideappsettings.json, through theDataProtection__CertificatePasswordenvironment variable. To create the certificate, see Data Protection Certificate (.pfx).- The outcome: one instance opens what another protected, a recreated pod still opens the old tokens, and the keys are stored encrypted on the volume.
Without a shared volume, replace KeysPath with the ReadKeys and WriteKey callbacks (see
Custom storage with ReadKeys and WriteKey) or with a provider
in ConfigureDataProtection. The lock accepts all of them.
Other risks
The lock does not check these. Before running more than one instance, also check:
- Redis without persistence β without AOF or RDB, or with a
maxmemory-policythat evicts keys (allkeys-lru), Redis loses the key ring. Use persistence andnoeviction. - Key certificate β if the
.pfxis lost, or replaced without keeping the old one, the key ring becomes unreadable. Keep it with the application secrets and keep the old one inUnprotectKeysWithAnyCertificatewhile there are keys protected by it. - Storage cleanup β Data Protection does not delete expired keys: they still open what they protected. Keep the storage out of cleanup routines and TTLs.
ApplicationNameβ without it, isolation depends on the application path, which can change with the image. Set the same value on every instance.
With AddTooarkSecurities
AddTooarkSecurities registers Data Protection when the DataProtection section exists and has at least one
key. If the application also calls AddTooarkDataProtection β to pass ConfigureDataProtection, for example β
the explicit call prevails in any order: AddTooarkSecurities does not reapply the section on top of it.
π§ Password Hashing
IPasswordHashService hashes passwords with PBKDF2-HMAC-SHA256, native to .NET (Rfc2898DeriveBytes.Pbkdf2),
with a random salt per password and 600.000 iterations by default β the current OWASP recommendation. The
Password value object of Tooark.ValueObjects validates and masks a password; this service is what goes to the
database.
public class AccountService(IPasswordHashService passwords, IUserRepository users)
{
public async Task RegisterAsync(string login, string password)
{
var user = new User(login, passwordHash: passwords.Hash(password));
await users.AddAsync(user);
}
public async Task<bool> LoginAsync(string login, string password)
{
var user = await users.FindByLoginAsync(login);
if (user is null || !passwords.Verify(password, user.PasswordHash))
{
return false;
}
// Parameters changed since this hash was written: rewrite it while the password is at hand
if (passwords.NeedsRehash(user.PasswordHash))
{
user.PasswordHash = passwords.Hash(password);
await users.UpdateAsync(user);
}
return true;
}
}
Hash format
$pbkdf2-sha256$i=600000$<salt in Base64>$<hash in Base64>
The PHC string carries the algorithm and the parameters, so the service keeps validating hashes written with
older parameters and NeedsRehash points out which ones to rewrite. Salt and hash use unpadded Base64, as the
format prescribes; Verify also accepts the padded form.
HashthrowsPasswordHash.PasswordNotProvidedfor a null or empty password.Verifynever throws: a null password, a null hash or a hash in another format (another algorithm, a plain text) returnsfalse.NeedsRehashreturnstruewhen the iterations, the salt size or the hash size differ from the current options, and also for a hash it cannot read.
Why PBKDF2 and not Argon2
.NET has no native Argon2. Shipping it here would force a third-party library on every consumer of the package, against the family's dependency policy. PBKDF2-HMAC-SHA256 with 600.000 iterations is the OWASP-recommended configuration for the algorithm, and the PHC prefix leaves room for another algorithm to coexist in the same column in the future: an old PBKDF2 hash keeps validating and is rewritten on the next login.
Tuning
Each login costs one derivation; so does each attempt of an attacker who stole the hashes. Measure the time on
your production hardware and raise Iterations while the login stays within budget (tens of milliseconds are
typical). Lowering below 100.000 is refused at startup (Options.PasswordHash.IterationsTooLow;100000).
π« Secure Tokens, TOTP and Recovery Codes
Three static classes cover the tokens an application hands to its users. None of them needs registration or configuration.
SecureToken β reset links, confirmations and API keys
// Issue: the token goes to the user (link, e-mail, API key), only the hash goes to the database
var token = SecureToken.Create(); // 32 random bytes in Base64Url (43 characters)
var hash = SecureToken.Hash(token); // SHA-256 in Base64Url, deterministic: index the column
await resets.StoreAsync(userId, hash, expiresAt: DateTime.UtcNow.AddHours(1));
// Redeem: find the record by the hash of what came back, then compare in constant time
var record = await resets.FindByHashAsync(SecureToken.Hash(received));
if (record is null || record.ExpiresAt < DateTime.UtcNow || !SecureToken.Verify(received, record.Hash))
{
return Results.Unauthorized();
}
The hash is SHA-256 without salt or cost factor on purpose: the token has at least 128 random bits, so brute
force is infeasible even with a fast hash, and a deterministic hash lets the record be found by it. Slow,
salted hashing is for passwords, which have little entropy (IPasswordHashService). Create accepts 16 to 1024
bytes; Verify returns false for anything missing or malformed, never throws. Hash throws
SecureToken.TokenNotProvided (BadRequestException) for a null, empty or blank token.
SecureTokenor Data Protection?SecureTokenis an opaque value: the hash lives in the database, so the token is revocable, can be single-use (delete the record on redemption) and lasts as long as the record does. The Data Protection protector (link token) carries its own encrypted content and needs no table, but only suits short lifetimes and cannot be revoked without separate tracking. For new tokens, preferSecureToken.CreateoverGenerateString.TokenfromTooark.Utils, which only generates the text and has no hash or verification.
Totp β second factor with authenticator apps
RFC 6238 over HMAC-SHA1, 6 digits and 30-second steps: the configuration Google Authenticator, Microsoft Authenticator and similar apps expect.
// Enrollment: generate the secret, store it encrypted, show the QR code built from the URI
var secret = Totp.GenerateSecret(); // Base32, 20 bytes
user.TotpSecret = crypto.Encrypt(secret); // ICryptographyService: whoever reads it generates valid codes
var uri = Totp.BuildUri(secret, issuer: "MyApp", account: user.Email); // otpauth://totp/MyApp:ana%40empresa.com?secret=...
// Confirm the enrollment with the first code the app shows
if (!Totp.Verify(secret, typedCode, lastUsedStep: -1, out var step))
{
return Results.BadRequest();
}
user.TotpLastUsedStep = step; // the same code is never accepted twice
// Login: verify against the stored secret and the last accepted step
var secret = crypto.Decrypt(user.TotpSecret);
if (!Totp.Verify(secret, typedCode, user.TotpLastUsedStep, out var step))
{
return Results.Unauthorized();
}
user.TotpLastUsedStep = step;
- Clock tolerance:
window(default 1) accepts the previous and the next step besides the current one β 30 seconds each way. All the steps are computed and compared in constant time, even after a match. - Replay protection: steps equal to or earlier than
lastUsedStepare refused. Store thematchedStepof every accepted code and pass it back on the next verification; pass a negative value before the first one. - A missing code, with the wrong length or with non-digit characters returns
false; spaces are ignored. An undecodable secret throwsTotp.InvalidSecret(InternalServerErrorException), because a corrupt secret would silently lock the user out. It is an internal error, not a request error: the secret comes from the database or the service, never from the user. BuildUrithrowsTotp.IssuerNotProvidedorTotp.AccountNotProvided(BadRequestException) for an empty issuer or account. Out-of-rangedigits,periodSeconds,windowand sizes throwArgumentOutOfRangeException: they are caller errors, not input data, so they have no translation key.Compute(secret, step, digits)andGetTimeStep(at, period)expose the pieces for tests and for showing a code server-side;TimeProvideronVerifylets a test drive the clock.digits(6 to 8) andperiodSecondsare configurable, but not every app honours values other than 6 and 30.
RecoveryCodes β when the authenticator is lost
// Enrollment: generate, show once, store only the hashes
var codes = RecoveryCodes.Generate(); // 10 codes like "7KQ2M-8XR4N"
user.RecoveryCodeHashes = codes
.Select(code => SecureToken.Hash(RecoveryCodes.Normalize(code)))
.ToList();
// Redeem: normalize what the user typed (case, hyphens, spaces), find the hash, delete it
var normalized = RecoveryCodes.Normalize(typedCode);
var match = user.RecoveryCodeHashes.FirstOrDefault(hash => SecureToken.Verify(normalized, hash));
if (match is null)
{
return Results.Unauthorized();
}
user.RecoveryCodeHashes.Remove(match); // each code is worth one use
The alphabet has no 0/O nor 1/I, so a printed code is typed without ambiguity. Generate returns distinct
codes, 10 of 10 characters by default (1 to 50 codes, 8 to 32 characters).
π Usage Examples
JWT - Creating and Validating a Token
Configuration with HMAC (Symmetric)
{
"Jwt": {
"Algorithm": "HS256",
"Secret": "my-super-secure-secret-key-32chars",
"Issuer": "my-api",
"Audience": "my-clients",
"ExpirationTime": 60
}
}
Configuration with RSA (Asymmetric)
{
"Jwt": {
"Algorithm": "RS256",
"PrivateKey": "MIIEvQIBADANBgkqh...base64-private-key...",
"PublicKey": "MIIBIjANBgkqhkiG9w...base64-public-key...",
"Issuer": "my-api",
"Audience": "my-clients",
"ExpirationTime": 60
}
}
Creating a Token
public class AuthController : ControllerBase
{
private readonly IJwtTokenService _jwtService;
public AuthController(IJwtTokenService jwtService)
{
_jwtService = jwtService;
}
[HttpPost("login")]
public IActionResult Login(LoginRequest request)
{
// Validate credentials...
// Create the token data
var tokenData = new JwtTokenDto(
id: user.Id,
login: user.Email,
security: user.SecurityStamp
);
// Generate the token
var token = _jwtService.Create(tokenData);
return Ok(new { Token = token });
}
// With a custom audience and extra claims
[HttpPost("login-custom")]
public IActionResult LoginCustom(LoginRequest request)
{
var tokenData = new JwtTokenDto(user.Id, user.Email, user.SecurityStamp);
var extraClaims = new[]
{
new Claim("role", "admin"),
new Claim("department", "IT")
};
var token = _jwtService.Create(tokenData, audience: "mobile-app", extraClaims: extraClaims);
return Ok(new { Token = token });
}
}
Validating a Token
The Microsoft.IdentityModel handler exposes validation only asynchronously, so ValidateAsync is the
direct path and Validate is the synchronous wrapper. In code that is already asynchronous, prefer
ValidateAsync:
[HttpGet("validate")]
public async Task<IActionResult> ValidateTokenAsync([FromHeader] string authorization)
{
var token = authorization.Replace("Bearer ", "");
var result = await _jwtService.ValidateAsync(token);
if (!string.IsNullOrEmpty(result.ErrorToken))
{
return Unauthorized(new { Error = result.ErrorToken });
}
return Ok(new { UserId = result.Id, Login = result.Login });
}
In synchronous code, the blocking overload delivers the same result:
[HttpGet("validate")]
public IActionResult ValidateToken([FromHeader] string authorization)
{
var token = authorization.Replace("Bearer ", "");
var result = _jwtService.Validate(token);
if (!string.IsNullOrEmpty(result.ErrorToken))
{
return Unauthorized(new { Error = result.ErrorToken });
}
return Ok(new
{
UserId = result.Id,
Login = result.Login,
// Or using the helpers
GuidId = result.GetGuidId,
IntId = result.GetIntId
});
}
Reading extra claims
The extra claims passed to Create come back in UserTokenDto. The Claims property holds every claim
in the token β the user's, the extra ones and the ones registered by the issuer (exp, iat, iss,
aud) β and the methods below read a claim by type. Like Id, Login and Security, a missing claim
does not throw:
| Method | Returns |
|---|---|
GetClaim(type) |
The claim's first value, or empty when it does not exist |
GetClaim<T>(type) |
The converted value (Guid, int, bool, decimal...), or the default |
GetClaims(type) |
Every value of the claim (roles, permissions), or an empty list |
HasClaim(type) |
Whether the claim exists in the token, even with an empty value |
// Creation: the extra claims go into the token
var extraClaims = new[]
{
new Claim("tenant", tenantId.ToString()),
new Claim("role", "admin"),
new Claim("role", "user")
};
var token = _jwtService.Create(tokenData, extraClaims: extraClaims);
// Validation: the same claims come out in UserTokenDto
var result = await _jwtService.ValidateAsync(token);
var tenant = result.GetClaim<Guid>("tenant"); // Guid.Empty when missing or invalid
var roles = result.GetClaims("role"); // ["admin", "user"]
A claim repeated at creation becomes an array in the payload and comes back as one claim per value: use
GetClaimsto read them all.GetClaim<T>converts with the invariant culture, so decimal numbers use a dot (1234.56).
To give the application's own claims a name and a type, keep the names in UserTokenDto extensions in
the application project. The rest of the code reads properties, without repeating strings:
public static class AppClaims
{
public const string Tenant = "tenant";
public const string Role = "role";
}
public static class UserTokenDtoExtensions
{
public static Guid GetTenantId(this UserTokenDto user) => user.GetClaim<Guid>(AppClaims.Tenant);
public static IReadOnlyList<string> GetRoles(this UserTokenDto user) => user.GetClaims(AppClaims.Role);
}
// Usage
var tenantId = result.GetTenantId();
With C# 14 (.NET 10 SDK), the same shortcuts can be extension properties:
public static class UserTokenDtoExtensions
{
extension(UserTokenDto user)
{
public Guid TenantId => user.GetClaim<Guid>(AppClaims.Tenant);
public IReadOnlyList<string> Roles => user.GetClaims(AppClaims.Role);
}
}
// Usage
var tenantId = result.TenantId;
Cryptography - Encrypt and Decrypt
Configuration
{
"Cryptography": {
"Algorithm": "GCM",
"SecretBase64": "32-byte-key-in-base64"
}
}
Using ICryptographyService
public class SensitiveDataService
{
private readonly ICryptographyService _crypto;
public SensitiveDataService(ICryptographyService crypto)
{
_crypto = crypto;
}
public string ProtectSensitiveData(string plainText)
{
// Returns the encrypted text in Base64
return _crypto.Encrypt(plainText);
}
public string UnprotectData(string encryptedText)
{
// Returns the original decrypted text
return _crypto.Decrypt(encryptedText);
}
}
Full Example
// Configure in Program.cs (registers ICryptographyService as a singleton)
builder.Services.AddTooarkCryptography(builder.Configuration);
// Use in the service
public class UserService
{
private readonly ICryptographyService _crypto;
public UserService(ICryptographyService crypto)
{
_crypto = crypto;
}
public void SaveUser(User user)
{
// Encrypt sensitive data before saving
user.CreditCard = _crypto.Encrypt(user.CreditCard);
user.SSN = _crypto.Encrypt(user.SSN);
// Save to the database...
}
public User GetUser(int id)
{
var user = // Fetch from the database...
// Decrypt sensitive data
user.CreditCard = _crypto.Decrypt(user.CreditCard);
user.SSN = _crypto.Decrypt(user.SSN);
return user;
}
}
Data Protection - Protecting a Link Token
With Data Protection registered, any service can create its own protector. The purpose isolates each use: a protector with another purpose cannot open these tokens.
public class InviteService
{
private readonly IDataProtector _protector;
public InviteService(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("Invites");
}
public string CreateToken(Guid inviteId) => _protector.Protect(inviteId.ToString());
public Guid? ReadToken(string token)
{
try
{
return Guid.Parse(_protector.Unprotect(token));
}
catch (CryptographicException)
{
// Tampered token or one protected by another key ring
return null;
}
}
}
For a token that expires on its own, use
provider.CreateProtector("Invites").ToTimeLimitedDataProtector()and pass the lifetime toProtect(packageMicrosoft.AspNetCore.DataProtection.Extensions, already included in ASP.NET Core).
π Generating Keys
Key for HMAC (HS256/HS384/HS512)
# Generate a random 32-byte (256-bit) key for HS256
openssl rand -base64 32
# Generate a random 64-byte (512-bit) key for HS512
openssl rand -base64 64
AES keys for SecretBase64 and Keys
# One random 32-byte key in Base64, for SecretBase64 or for each entry of Keys
openssl rand -base64 32
// Or in .NET
Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
RSA Keys (RS256/PS256)
# Generate a 2048-bit RSA private key
openssl genrsa -out private.pem 2048
# Extract the public key
openssl rsa -in private.pem -pubout -out public.pem
# Convert to the PKCS8 format (recommended)
openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in private.pem -out private_pkcs8.pem
# Get the key in Base64 (without headers)
cat private_pkcs8.pem | grep -v "BEGIN\|END" | tr -d '\n'
cat public.pem | grep -v "BEGIN\|END" | tr -d '\n'
ECDsa Keys (ES256/ES384/ES512)
# ES256 (P-256)
openssl ecparam -genkey -name prime256v1 -noout -out ec_private.pem
openssl ec -in ec_private.pem -pubout -out ec_public.pem
# ES384 (P-384)
openssl ecparam -genkey -name secp384r1 -noout -out ec_private.pem
# ES512 (P-521)
openssl ecparam -genkey -name secp521r1 -noout -out ec_private.pem
# Convert to PKCS8
openssl pkcs8 -topk8 -nocrypt -in ec_private.pem -out ec_private_pkcs8.pem
Data Protection Certificate (.pfx)
# Self-signed 2048-bit RSA certificate, valid for 2 years
openssl req -x509 -newkey rsa:2048 -sha256 -days 730 -nodes -subj "/CN=dataprotection" \
-keyout dataprotection.key -out dataprotection.crt
# Bundle the certificate and the private key into PKCS#12
openssl pkcs12 -export -inkey dataprotection.key -in dataprotection.crt \
-out dataprotection.pfx -passout pass:certificate-password
The certificate must be RSA (the XML encryption of the keys does not accept ECDSA). When replacing it, keep the old one available with
UnprotectKeysWithAnyCertificateinConfigureDataProtectionuntil the keys it protected expire.
π Dependencies
| Package | Version | Description |
|---|---|---|
Tooark.Exceptions |
4.x | Exceptions (e.g. BadRequestException) |
Microsoft.AspNetCore.Authentication.JwtBearer |
8.x/10.x | JWT authentication for ASP.NET Core |
Microsoft.AspNetCore.DataProtection |
8.x/10.x | Data Protection, standalone package that runs on the base runtime |
π― Best Practices
JWT
- Use asymmetric algorithms (RS/PS/ES) in production - Allows validating tokens without exposing the signing key
- Configure
ExpirationTimeappropriately - Short-lived tokens are safer - Use
IssuerandAudience- Prevents tokens from being misused across applications - Store keys in a Secret Manager - Never commit keys to source code
- Register
AddTooarkJwtBearerinstead of a hand-writtenAddJwtBearer- Same key, issuer and audience as the issuer, validated at startup - Set
EmitLegacyClaimsandEmitStandardClaimsexplicitly - The v5 defaults invert; explicit flags keep the tokens stable across the upgrade - Read claims through
TooarkClaimNamesorUserTokenDto- They follow both naming sets
Cryptography
- Prefer GCM over CBC - GCM provides built-in authentication
- Never use CBCUnsafe for new data - Decrypt-only mode for compatibility with legacy systems
- Use
SecretBase64with a random 32-byte key - The key is used directly, without derivation; the textSecretis obsolete and removed in v5 - Generate random keys - Use
openssl rand -base64 32orRandomNumberGenerator.GetBytes(32) - Adopt
Keysbefore the first rotation is urgent - Values written with identified keys rotate without a big-bang re-encryption - Never remove a key with values still encrypted by it - Check with
KeyIdOfor re-encrypt on read first
Password hashing
- Store only the PHC string - Never the password, never a fast hash of it
- Call
NeedsRehashafter a successfulVerify- The hash is rewritten while the password is at hand - Raise
Iterationswith the hardware - Measure the login time and keep it within budget; never go below the minimum - Limit attempts - A slow hash does not replace rate limiting on the login endpoint
Tokens and second factor
- Store hashes, not tokens -
SecureToken.Hashfor reset tokens, API keys and recovery codes - Give tokens an expiration - The hash does not expire on its own; keep an
ExpiresAtnext to it - Encrypt the TOTP secret at rest - Whoever reads it generates valid codes; use
ICryptographyService - Persist
matchedStep- Without it, a code intercepted within the window is accepted twice - Show recovery codes once - And invalidate each one on use
Data Protection
- Set
ApplicationName- Isolation stays the same on every instance, regardless of the install path - Share the key ring across instances - A persistent volume in
KeysPath, theReadKeysandWriteKeycallbacks or a storage throughConfigureDataProtection - Turn on
RequirePersistentKeyStoragein containers - The application no longer starts with the keys tied to the instance - In the callbacks, only insert and read everything - An overwritten, filtered or deleted key makes what it protected unreadable
- Protect the keys at rest - With
KeysPathor callbacks and no certificate, the keys are written unencrypted, on any operating system - Do not use it for long-lived data - Encrypted database columns belong to
ICryptographyService
β οΈ Error Codes and Solutions
| Service | Message | Description | Solution | Exception |
|---|---|---|---|---|
CryptographyService |
Options.NotConfigured |
Options not configured |
Configure CryptographyOptions |
InternalServerError |
CryptographyService |
Options.Cryptography.SecretNotConfigured |
No key configured | Configure Secret or SecretBase64 in CryptographyOptions |
InternalServerError |
CryptographyService |
Options.Cryptography.SecretBase64Invalid |
SecretBase64 is not valid Base64 |
Provide a valid Base64 value in SecretBase64 |
InternalServerError |
CryptographyService |
Options.Cryptography.SecretBase64InvalidSize |
SecretBase64 is not 32 bytes |
Use a key of exactly 32 bytes (AES-256) | InternalServerError |
CryptographyService |
Options.Cryptography.AlgorithmDecryptOnly |
CBCUnsafe used to encrypt |
Use CBCUnsafe only to decrypt legacy data |
InternalServerError |
CryptographyService |
Cryptography.PlainTextNotProvided |
PlainText not provided |
Provide the plain text to encrypt | BadRequest |
CryptographyService |
Cryptography.CipherTextNotProvided |
CipherText not provided |
Provide the encrypted text to decrypt | BadRequest |
CryptographyService |
Cryptography.InvalidCipherText |
Invalid CipherText |
Provide a valid encrypted text to decrypt | BadRequest |
KeyedCryptographyService |
Options.Cryptography.Keys.NotConfigured |
Keyed service without keys | Fill Keys or use the single-key Secret/SecretBase64 |
InternalServerError |
KeyedCryptographyService |
Options.Cryptography.CurrentKeyId.NotConfigured |
Keys without CurrentKeyId |
Point CurrentKeyId to one of the identifiers in Keys |
InternalServerError |
KeyedCryptographyService |
Options.Cryptography.CurrentKeyId.NotFound;{id} |
CurrentKeyId not among Keys |
Use an identifier that exists in Keys |
InternalServerError |
KeyedCryptographyService |
Options.Cryptography.KeyId.Invalid;{id} |
Identifier with a dot, space or other invalid character | Use only letters, digits, hyphen and underscore | InternalServerError |
KeyedCryptographyService |
Options.Cryptography.Keys.Invalid;{id} |
Key that is not 32 bytes in Base64 | Generate the key with openssl rand -base64 32 |
InternalServerError |
KeyedCryptographyService |
Cryptography.KeyNotFound;{id} |
Value encrypted with a key that is not configured | Put the key back in Keys; only remove keys after re-encrypting |
BadRequest |
KeyedCryptographyService |
Cryptography.LegacyKeyNotConfigured |
Value without prefix and no Secret/SecretBase64 |
Keep the legacy key until every legacy value is re-encrypted | BadRequest |
PasswordHashService |
Options.NotConfigured |
Options not configured |
Register with AddTooarkPasswordHash |
InternalServerError |
PasswordHashService |
Options.PasswordHash.IterationsTooLow;100000 |
Iterations below the minimum |
Use at least 100.000 iterations (default 600.000) | InternalServerError |
PasswordHashService |
Options.PasswordHash.SaltSizeTooSmall;16 |
SaltSize below the minimum |
Use at least 16 bytes | InternalServerError |
PasswordHashService |
Options.PasswordHash.HashSizeTooSmall;32 |
HashSize below the minimum |
Use at least 32 bytes | InternalServerError |
PasswordHashService |
PasswordHash.PasswordNotProvided |
Null or empty password in Hash |
Validate the password before hashing | BadRequest |
SecureToken |
SecureToken.TokenNotProvided |
Null, empty or blank token in Hash |
Validate the token before hashing | BadRequest |
Totp |
Totp.InvalidSecret |
Secret that is not a valid Base32 value | Check the stored secret; enroll the second factor again | InternalServerError |
Totp |
Totp.IssuerNotProvided |
Null or empty issuer in BuildUri |
Provide the application name | BadRequest |
Totp |
Totp.AccountNotProvided |
Null or empty account in BuildUri |
Provide the account identification, such as the e-mail | BadRequest |
AddTooarkDataProtection |
Options.DataProtection.KeyLifetimeTooShort;7 |
KeyLifetimeDays below the minimum |
Use at least 7 days, or leave it null for the default 90 | InternalServerError |
AddTooarkDataProtection |
Options.DataProtection.CertificateAmbiguous |
CertificatePath and CertificateThumbprint together |
Provide only one of them | InternalServerError |
AddTooarkDataProtection |
Options.DataProtection.CertificatePathNotConfigured |
CertificatePassword without CertificatePath |
Provide CertificatePath or remove the password |
InternalServerError |
AddTooarkDataProtection |
Options.DataProtection.CertificateNotFound;{value} |
File or thumbprint not found | Check the path, or install the certificate in the My store |
InternalServerError |
AddTooarkDataProtection |
Options.DataProtection.CertificateInvalid |
Unreadable .pfx or wrong password |
Check the file and CertificatePassword |
InternalServerError |
AddTooarkDataProtection |
Options.DataProtection.CertificateWithoutPrivateKey |
Certificate without a private key | Export the .pfx with the private key |
InternalServerError |
AddTooarkDataProtection |
Options.DataProtection.CertificateNotRsa |
Certificate without an RSA key | Use an RSA certificate | InternalServerError |
AddTooarkDataProtection |
Options.DataProtection.KeyStorageNotConfigured |
Lock on and no key storage configured | Set a shared KeysPath, the callbacks or an external storage |
InternalServerError |
AddTooarkDataProtection |
Options.DataProtection.KeyCallbacksIncomplete |
Only one of the ReadKeys and WriteKey callbacks |
Provide both callbacks | InternalServerError |
AddTooarkDataProtection |
Options.DataProtection.KeyStorageAmbiguous |
KeysPath together with ReadKeys and WriteKey |
Provide a single key storage | InternalServerError |
JwtTokenService |
Options.NotConfigured |
Options not configured |
Configure JwtOptions |
InternalServerError |
JwtTokenService |
Options.Jwt.SecretNotConfigured |
Secret not configured |
Configure Secret in JwtOptions for a symmetric token |
InternalServerError |
JwtTokenService |
Options.Jwt.SecretTooShort |
Secret below the algorithm minimum |
Use at least 32/48/64 bytes for HS256/HS384/HS512 | InternalServerError |
JwtTokenService |
Options.Jwt.KeysNotConfigured |
Private and Public not configured |
Configure the keys in JwtOptions for an asymmetric token |
InternalServerError |
JwtTokenService |
Options.Jwt.PrivateKey.InvalidSize |
Invalid Private key size |
Use a Private key of at least 2048 bits |
InternalServerError |
JwtTokenService |
Options.Jwt.PublicKey.InvalidSize |
Invalid Public key size |
Use a Public key of at least 2048 bits |
InternalServerError |
JwtTokenService |
Options.Jwt.PrivateKey.InvalidCurve |
Invalid Private key curve |
Use a Private key with the correct curve |
InternalServerError |
JwtTokenService |
Options.Jwt.PublicKey.InvalidCurve |
Invalid Public key curve |
Use a Public key with the correct curve |
InternalServerError |
JwtTokenService |
Options.Jwt.InvalidKey |
Invalid key | Use valid keys for the chosen algorithm | InternalServerError |
JwtTokenService |
Options.Jwt.AlgorithmNotSupported |
Unsupported algorithm | Use a supported algorithm | InternalServerError |
JwtTokenService |
Options.Jwt.KeyNotConfigured;PrivateKey |
Private key not configured |
Configure PrivateKey in JwtOptions to generate a token |
InternalServerError |
JwtTokenService |
Options.Jwt.KeyNotConfigured;PublicKey |
Public key not configured |
Configure PublicKey in JwtOptions to validate a token |
InternalServerError |
JwtTokenService |
Options.Jwt.ClaimsNotConfigured |
EmitLegacyClaims and EmitStandardClaims both off |
Turn on at least one of the two claim sets | InternalServerError |
AddTooarkJwtBearer |
Options.Jwt.KeyNotConfigured;PublicKey |
No validation key for the Bearer scheme |
Configure Secret (HMAC) or PublicKey in the Jwt section |
InternalServerError |
JwtTokenService |
Token.Expired |
Expired token | Generate a new token | N/A |
JwtTokenService |
Token.InvalidSignature |
Token with an invalid signature | Use only tokens with a valid signature | N/A |
JwtTokenService |
Token.Invalid |
Invalid token | Use only valid tokens | N/A |
JwtTokenService |
InternalServerError |
Internal server error | Check the logs for details | N/A |
π€ Contributing
Contributions are welcome! Start with CONTRIBUTING.md β it covers the development workflow, the coding and commit conventions and the pull request checklist. Bugs and feature requests go through the issue templates of the Tooark repository.
By participating you agree to the Code of Conduct.
π Help & Security
- β Questions, bugs, feature ideas β see SUPPORT.md for the right channel
- π Security vulnerabilities β do not open a public issue; follow SECURITY.md
π Support
If Tooark helps your projects, consider supporting its development:
- π GitHub Sponsors
- β Ko-fi
Every contribution helps keep the project maintained and improving. Thank you! π
π License
This project is licensed under the BSD 3-Clause License.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. 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
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.15)
- Microsoft.AspNetCore.DataProtection (>= 10.0.15)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.15)
- Microsoft.Extensions.FileProviders.Abstractions (>= 10.0.15)
- Microsoft.Extensions.Options (>= 10.0.15)
- Tooark.Exceptions (>= 4.9.0)
-
net8.0
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 8.0.34)
- Microsoft.AspNetCore.DataProtection (>= 8.0.34)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Microsoft.Extensions.FileProviders.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.2)
- Tooark.Exceptions (>= 4.9.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Tooark.Securities:
| Package | Downloads |
|---|---|
|
Tooark
Package with all Tooark resources for .NET applications. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 4.11.0 | 118 | 11/21/2026 |
| 4.10.0 | 136 | 11/18/2026 |
| 4.9.0 | 133 | 11/16/2026 |
| 4.8.0 | 150 | 11/15/2026 |
| 4.7.3 | 121 | 11/11/2026 |
| 4.7.2 | 114 | 11/3/2026 |
| 4.7.1 | 228 | 10/17/2026 |
| 4.7.0 | 500 | 9/30/2026 |
| 4.6.0 | 166 | 9/29/2026 |
| 4.5.0 | 125 | 9/29/2026 |
| 4.4.0 | 118 | 9/28/2026 |
| 4.3.0 | 129 | 9/26/2026 |
| 4.2.1 | 132 | 9/25/2026 |
| 4.2.0 | 137 | 9/20/2026 |
| 4.1.0 | 122 | 9/18/2026 |
| 4.0.1 | 134 | 8/25/2026 |
| 3.3.7 | 90 | 11/15/2026 |
| 3.3.6 | 126 | 9/18/2026 |
| 2.3.6 | 90 | 11/15/2026 |
| 2.3.5 | 114 | 9/18/2026 |