How to Implement Data Encryption at Rest in ASP.NET Core 10 Using SQL Server Always Encrypted (2026)

SQL Server Always Encrypted protects selected columns by having a compatible client encrypt and decrypt values. An ASP.NET Core application uses Microsoft.Data.SqlClient with column encryption enabled and access to the key provider. This lab stores a synthetic tax ID in a randomized encrypted column and exposes only a masked read.

How does Always Encrypted work?

Read SQL key metadata. Unwrap CEK using key provider. Encrypt parameter in SqlClient. Store ciphertext in SQL Server.
Read SQL key metadata. Unwrap CEK using key provider. Encrypt parameter in SqlClient. Store ciphertext in SQL Server.

A column encryption key encrypts values. SQL Server stores its wrapped value as metadata. A column master key in an external key store protects the column encryption key. The driver reads metadata, obtains permission to unwrap the key, and encrypts or decrypts values at the client.

Control Typical scope
TLS Protects data in transit between client and server
Transparent Data Encryption Encrypts database files and backups at rest when enabled
Always Encrypted Protects selected column values at the client boundary
Application authorization Controls who can invoke business operations

This application processes plaintext when a caller writes a value and when a privileged driver reads it. Protect the process, logs, secret store and identity. Use TLS with certificate validation alongside Always Encrypted. See Always Encrypted overview.

Provision the keys and schema

Use an isolated SQL Server database, a .NET 10 SDK, and SQL Server Management Studio. For a Windows development lab, create or select a certificate in the Windows certificate store for the lab identity. The app runs under an account with private-key access. In SSMS, open the database Security and Always Encrypted Keys nodes. Create a column master key referencing that certificate and a column encryption key named CEK_Customer protected by it. Create the database user for the app identity, or change the grant target in the sample to match the real user.

schema.sql
-- Provision CEK_Customer in this database using the SSMS key wizard first.
CREATE TABLE dbo.CustomerSecret (
    Id int NOT NULL PRIMARY KEY,
    TaxId char(9) COLLATE Latin1_General_BIN2
      ENCRYPTED WITH (
        COLUMN_ENCRYPTION_KEY = CEK_Customer,
        ENCRYPTION_TYPE = RANDOMIZED,
        ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256'
      ) NULL
);
INSERT dbo.CustomerSecret(Id) VALUES(1);
-- Grant these permissions to your existing application database principal:
GRANT SELECT, UPDATE ON dbo.CustomerSecret TO [VaultApp];
GRANT VIEW ANY COLUMN MASTER KEY DEFINITION TO [VaultApp];
GRANT VIEW ANY COLUMN ENCRYPTION KEY DEFINITION TO [VaultApp];

Create the keys before applying the script. Keep the key provisioning identity separate from the application identity. The app needs rights to use the key metadata and read or update the intended data. Restrict access to the private key outside SQL Server. An external managed key store requires its documented provider, registration and permissions. Plan certificate or key backup and rotation before storing data that matters.

Randomized encryption is suitable when you retrieve records by an unencrypted surrogate ID and do not need equality searches on the secret. Deterministic encryption enables some equality operations and reveals repeated values. That matters with predictable or low-cardinality data. Secure enclave scenarios have different capabilities and deployment requirements. The lab uses ordinary Always Encrypted without an enclave.

Build the ASP.NET Core API

Set ConnectionStrings__Vault using local secrets. The code enables column encryption and binds the secret as char(9) to match the schema. The ForceColumnEncryption flag makes the write fail if driver metadata indicates the parameter would be sent without encryption. The plain ID supports locating a row without comparing the encrypted value.

Sample.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Data.SqlClient" Version="6.1.*" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.*" />
  </ItemGroup>
</Project>
Program.cs
using System.Data;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Data.SqlClient;

var b = WebApplication.CreateBuilder(args);
b.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
b.Services.AddAuthorization(o => o.AddPolicy("vault", p => p.RequireRole("VaultOperator")));
var app = b.Build();
var cs = new SqlConnectionStringBuilder(b.Configuration.GetConnectionString("Vault")
    ?? throw new InvalidOperationException("Set ConnectionStrings__Vault."))
{
    ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Enabled
}.ConnectionString;

app.MapPut("/customers/{id:int}/tax-id", async (int id, TaxId body, CancellationToken ct) =>
{
    if (id <= 0 || body.Value is not { Length: 9 } ||
        body.Value.Any(c => !char.IsAsciiDigit(c))) return Results.BadRequest();
    await using var db = new SqlConnection(cs);
    await db.OpenAsync(ct);
    await using var cmd = new SqlCommand(
        "UPDATE dbo.CustomerSecret SET TaxId=@value WHERE Id=@id;", db);
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    var parameter = cmd.Parameters.Add("@value", SqlDbType.Char, 9);
    parameter.Value = body.Value;
    parameter.ForceColumnEncryption = true;
    return await cmd.ExecuteNonQueryAsync(ct) == 1 ? Results.NoContent() : Results.NotFound();
}).RequireAuthorization("vault");

app.MapGet("/customers/{id:int}/tax-id", async (int id, HttpContext http, CancellationToken ct) =>
{
    http.Response.Headers.CacheControl = "no-store";
    await using var db = new SqlConnection(cs);
    await db.OpenAsync(ct);
    await using var cmd = new SqlCommand("SELECT TaxId FROM dbo.CustomerSecret WHERE Id=@id;", db);
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    var result = await cmd.ExecuteScalarAsync(ct);
    if (result is null) return Results.NotFound();
    return Results.Ok(new { last4 = result is string value ? value[^4..] : null });
}).RequireAuthorization("vault");
app.Run();

public sealed record TaxId(string? Value);

This API uses a VaultOperator role for the lab. For a real system, apply access control to the requested customer as well. An authorized operator still should see only the fields necessary for their workflow. Do not echo the submitted tax ID or capture it in request logs, APM payloads or problem responses.

Test success, masking and failure paths

Start the app with a development JWT configured for the local audience and a token carrying VaultOperator. The seed row has ID 1. Use only a synthetic value.

BASH
curl -i -X PUT -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{"value":"123456789"}' \
  http://localhost:5095/customers/1/tax-id
curl -i -H "Authorization: Bearer $TOKEN" \
  http://localhost:5095/customers/1/tax-id

Expect 204 from the write and a masked JSON result with last4 set to 6789. Invalid length should return 400. A user lacking the role should receive 403. As a lab administrator, query using a connection with column encryption disabled and inspect the ciphertext. Run a second isolated test with a principal lacking private-key access and verify that the encrypted read or write fails. Restore the lab permission afterward. Compile checks cannot substitute for this database and key-store test.

Plan EF Core integration and key rotation

EF Core uses the underlying SQL client. An entity property or value converter does not provision an Always Encrypted key or make arbitrary LINQ predicates translatable against encrypted data. Configure the connection and explicitly map the property type and length. Capture generated SQL and test actual parameter metadata. Use a parameterized SqlClient command when the encrypted parameter requires explicit ForceColumnEncryption or when generated SQL fails a supported operation.

A column master key rotation can rewrap the existing column encryption key. Keep both master key paths available during the rollout, update application access, verify reads and writes, and retire the old wrapping after all clients and recovery procedures have moved. Rotating the column encryption key itself requires re-encrypting column data. Test production-sized migration cost, locks, backup restore and rollback before scheduling it.

Include cold connections and warm connections in latency testing. Client-side metadata lookup, key access and encryption can affect query latency. Monitor latency and failures without exporting plaintext or key material. Review whether the chosen provider and driver cache keys or metadata, and how changes propagate to long-running instances.

Troubleshooting and operations

Symptom Check
Operand type clash Match parameter SQL type, size and precision to the target
Column key cannot be decrypted Check provider registration, private-key ACL and application identity
Key metadata permission denied Verify database grants for the column master and encryption key definitions
A restore cannot decrypt data Verify your key store and retained keys are available to the restored application

Can I encrypt an existing populated column by running this CREATE TABLE script? This creates a new table. Plan an existing-data migration using supported tooling and test its blocking, rollback and key access in a restored database.

Can I search the randomized tax ID? This lab looks up the customer by ID. Searching encrypted values needs a deliberately chosen encryption and query design.

Read Microsoft.Data.SqlClient Always Encrypted guidance, key provisioning, and the ASP.NET PB SQL Server CRUD guide.

Comments