Encryption
Introduction
The Crypt facade encrypts and decrypts values with authenticated encryption on top of ASP.NET Core Data Protection. Encrypted values cannot be read or modified without the key; a tampered payload is rejected on decryption. This is the counterpart of Laravel's Crypt facade, but payloads are not interchangeable with Laravel's.
Configuration
Like Laravel, encryption uses the application key, APP_KEY in your .env file:
APP_KEY=base64:2fl+Ktvkfl+Fuz4Qp/A75G2RTiWVA/ZoKZvp6fiiM10=dotblaze new creates .env with a fresh key. To make one yourself, run key:generate, which writes it to .env (--show only prints it):
dotblaze key:generateA key is base64: followed by 32 random bytes, or any string of at least 32 characters. Every server and worker with the same APP_KEY can decrypt each other's values. The same key also protects the authentication cookie, CSRF tokens, sessions, flash data, signed URLs, and live components.
WARNING
Keep APP_KEY secret and out of source control. Changing it logs every user out and makes values encrypted with the old key unreadable. key:generate therefore refuses to replace a key unless you pass --force.
Under the hood, DotBlaze derives an ASP.NET Core Data Protection key from APP_KEY and uses app.name as the application name. Without an APP_KEY, Data Protection creates and rotates its own keys and stores them in storage/framework/keys (change the folder with app.keys_path); several servers then have to share that folder.
To keep Data Protection's own keys in another store instead, leave APP_KEY empty and call the standard Data Protection API in a service provider:
using Microsoft.AspNetCore.DataProtection;
public class AppServiceProvider : Provider
{
public override void Register(IServiceCollection services, IConfiguration config)
{
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo("/var/dotblaze/keys"));
}
}Using the Encrypter
Encrypting a Value
Crypt.Encrypt serializes any value to JSON and encrypts it, returning a URL-safe string:
var token = Crypt.Encrypt(new { UserId = 1, Expires = DateTime.UtcNow.AddHours(1) });
var secret = Crypt.Encrypt("a plain string");Decrypting a Value
Crypt.Decrypt<T> decrypts the payload and deserializes it to T. If the payload is corrupt, has been tampered with, or was encrypted with a key that is no longer in the key ring, a DotBlaze.DecryptException is thrown:
public record ResetPayload(int UserId, DateTime Expires);
try
{
var payload = Crypt.Decrypt<ResetPayload>(token);
}
catch (DecryptException)
{
// invalid token
}NOTE
Encrypted values carry no expiry of their own. If a value should expire, include a timestamp in it, as above, and check it after decrypting.
Complete Example: Encrypted Payload Self-Check
The Blog template already configures Data Protection. This command exercises serialization and rejection of invalid ciphertext without printing a secret:
// app/Commands/EncryptionDemo.cs
using DotBlaze;
namespace Blog.Commands;
public record DemoPayload(long DocumentId, DateTimeOffset ExpiresAt);
public class EncryptionDemo : Command
{
public override string Signature => "demo:encryption";
public override Task<int> Handle()
{
var expected = new DemoPayload(42, Date.UtcNow.AddMinutes(10));
var token = Crypt.Encrypt(expected);
var actual = Crypt.Decrypt<DemoPayload>(token);
if (actual != expected || actual.ExpiresAt <= Date.UtcNow)
throw new InvalidOperationException("Payload verification failed.");
try
{
Crypt.Decrypt<DemoPayload>("not-a-valid-encrypted-payload");
throw new InvalidOperationException("Invalid ciphertext was accepted.");
}
catch (DecryptException)
{
Line("Round-trip succeeded; invalid ciphertext rejected.");
}
return Task.FromResult(0);
}
}Run dotblaze demo:encryption. Expected exit code: 0. This demonstrates encryption, not a password-reset implementation: use the password broker for single-use reset tokens. Encryption alone neither checks expiration nor prevents replay; those are application rules.