Encryption and blind indexes

This page covers field encryption. It shows how to mark a field as encrypted, where the keys live, what a copy of a table contains, how to find a row by an encrypted value, and how erasure makes every copy of the data unreadable. The code is the Shop sample.

Mark a field as encrypted

Add [Encrypted] to a personal property. Add [BlindIndex] as well if you need to look rows up by that value.

using Custodian;

namespace Shop;

/// <summary>
/// A customer account. Kept while the customer is active and deleted three years after their last activity:
/// the account exists to fulfil the contract, so it goes when the relationship does.
/// </summary>
[PersonalDataEntity(
    Purpose = Purposes.CustomerAccount,
    LawfulBasis = LawfulBasis.Contract,
    Retention = "P3Y",
    Anchor = RetentionAnchor.LastActivity,
    OnExpiry = ExpiryAction.Delete)]
public sealed class Customer
{
    public int Id { get; set; }

    [DataSubject]
    public Guid SubjectId { get; set; }

    [PersonalData(DataCategory.Identity)]
    public string Name { get; set; } = "";

    /// <summary>Encrypted with the customer's own key, so erasure makes every copy unreadable; the blind index keeps it findable.</summary>
    [PersonalData(DataCategory.Contact), Encrypted, BlindIndex]
    public string Email { get; set; } = "";

    [PersonalData(DataCategory.Contact)]
    public string Phone { get; set; } = "";
}

Custodian encrypts the value when the row is saved and decrypts it when the row is read. Your code sees a plain string. A sales clerk working for the customer-account purpose reads the email address as it was entered, as A_sales_clerk_reads_the_email_address_decrypted shows. Shipment encrypts the delivery address the same way.

Each value is encrypted with AES-256-GCM under a random 96-bit nonce of its own. The stored value starts with a short header that holds a format version and the id of the key. Custodian uses the cryptography that ships with .NET and no primitives of its own.

Encryption does not replace the purpose check. A reader outside the purpose is refused or masked exactly as for an unencrypted field. Roles and purposes covers that.

One key per data subject

Every data subject has a data key of their own. Custodian creates the key when you register the subject. Rows you save for that subject are then encrypted with it.

SubjectId subject;
using (processing.Begin(Purposes.CustomerAccount))
{
    subject = await subjects.RegisterAsync(newCustomer.Email, cancellationToken);
}

var customer = new Customer
{
    SubjectId = subject.Value,
    Name = newCustomer.Name,
    Email = newCustomer.Email,
    Phone = newCustomer.Phone,
};

using (processing.Begin(Purposes.CustomerAccount, subject))
{
    db.Customers.Add(customer);
    await db.SaveChangesAsync(cancellationToken);
}

The data key is stored in the database, wrapped by a key-encryption key. Each tenant has its own key-encryption key, and that key lives in the key store, outside the database. A copy of the database alone is therefore not enough to read an encrypted field.

Custodian keeps unwrapped keys in memory for five minutes by default. Change that with o.KeyStore.CacheKeysFor(...).

What a copy of the table contains

A backup, a replica or a stolen disk holds ciphertext in every encrypted column.

[Theory, EachProvider]
public async Task The_email_address_is_not_stored_in_the_clear(DatabaseProvider provider)
{
    await using var shops = await servers.OpenShop(provider);
    var astrid = await shops.Nordic.SignUp(Customers.Astrid());

    var stored = await shops.Nordic.BackUp("SELECT email FROM customers");

    stored.ShouldNotReveal(astrid.Email);
}

BackUp copies the column exactly as the database stores it. The same holds for the delivery address (The_delivery_address_is_not_stored_in_the_clear) and for the health data of the Clinic sample (A_clinical_note_is_stored_as_ciphertext).

Fields you do not mark stay readable in a copy. In the Shop sample that includes the customer's name and phone number. Mark every field whose exposure in a backup would matter.

Find a row by an encrypted value

The same value encrypts to different ciphertext every time, so the database cannot search an encrypted column. A blind index solves that for equality lookups. It is an HMAC-SHA256 of the value under a key that is separate from the encryption keys. Each tenant has its own blind-index key.

The subject registry uses a blind index for the identifier you register a subject under. The Shop sample registers each customer under their email address and finds them again the same way.

public async Task<Customer?> FindByEmailAsync(string email, CancellationToken cancellationToken)
{
    using var account = processing.Begin(Purposes.CustomerAccount);

    var subject = await subjects.FindAsync(email, cancellationToken);
    if (subject is not { } found)
    {
        return null;
    }

    return await db.Customers.SingleOrDefaultAsync(c => c.SubjectId == found.Value, cancellationToken);
}

The registry stores only the keyed hash of the email address, never the address itself.

[BlindIndex] on a property gives that column a blind index of its own. The EF Core adapter stores the keyed hash in a column next to the ciphertext and fills it on save. Code that writes its own SQL computes the hash to compare against with ICustodian.BlindIndexAsync.

A blind index answers "is this value equal to that one" and nothing else. It cannot sort, and it cannot match a prefix.

Crypto-shredding on erasure

Erasing a data subject destroys their data key. Every value encrypted with that key becomes unreadable wherever a copy of it exists, including backups taken before the erasure. You do not have to find and rewrite those copies.

[Theory, EachProvider]
public async Task A_backup_taken_before_erasure_cannot_be_decrypted_afterwards(DatabaseProvider provider)
{
    await using var shops = await servers.OpenShop(provider);
    var astrid = await shops.Nordic.SignUp(Customers.Astrid());
    var backup = await shops.Nordic.BackUp("SELECT email FROM customers");
    await shops.Nordic.PrivacyOffice.Erase(astrid);

    var restoring = () => shops.Nordic.RestoreEmails(backup);

    await Assert.ThrowsAsync<KeyShreddedException>(restoring);
}

RestoreEmails hands each stored value back to Custodian with ICustodian.DecryptAsync. That call is also how your own code decrypts a value it read with its own SQL. It passes the same checks as any other read of the field.

public Task<IReadOnlyList<string>> Restore<TEntity>(ColumnBackup backup, Expression<Func<TEntity, string>> field)
    where TEntity : class =>
    Use<ICustodian, IReadOnlyList<string>>(async custodian =>
    {
        var restored = new List<string>();
        foreach (var value in backup.AsEncrypted())
        {
            restored.Add(await custodian.DecryptAsync(field, value, Cancellation));
        }

        return restored;
    });

After the erasure the call throws KeyShreddedException. Custodian never falls back to plaintext.

Crypto-shredding protects encrypted fields only. Erasure also deletes or blanks the rows themselves. Data-subject rights describes the whole operation.

If you run several instances, the instance that performs the erasure forgets the key at once. The others can still decrypt until their cached copy of the key runs out, which is the cache lifetime above.

Key stores

The key store holds the key-encryption keys. You choose one when you register Custodian.

o.KeyStore.UseLocal(keyStore);

UseLocal comes from the Custodian.KeyStores.Local package. It keeps one key file per tenant in the directory you name. It is meant for development and tests and needs no licence key. Keep the directory out of source control.

Key stores for production keep the key-encryption keys in a cloud key vault. They need a licence key with a valid signature. Custodian checks the signature only and never the expiry date, so a lapsed licence adds warnings and does not stop a running system.

You can also supply your own store. Implement IKeyStore, which wraps a data key, unwraps it and destroys a tenant's key-encryption key, and register it with o.KeyStore.Use(...).

Next