You don't actually run C# encryption logic inside SQL Server. There's no supported way to load arbitrary C# code (or the .NET runtime) into the database engine the way SQL CLR historically allowed managed assemblies—and Microsoft has deprecated and locked down much of that surface for security reasons. What you do instead is move the encryption boundary: either encrypt in the application layer (C#) before data reaches SQL Server, or call encryption from C# via a SQL Server feature that does the work server-side (TDE, Always Encrypted, column-level ENCRYPTBYKEY). The key condition for every approach is that the encryption keys must live somewhere the database engine itself can't freely read if you want protection from DBAs and backups.
This guide lays out the realistic options, in the order most teams should evaluate them, with concrete C# and T-SQL where it matters.
First, Decide Where the Encryption Boundary Actually Sits
The phrase "build C# encryption into SQL Server" collapses two different architectures, and picking the wrong one is the most common failure.
Option A — Application-layer encryption (C# does the crypto). You encrypt in C# and hand ciphertext to SQL Server. The database stores opaque bytes. This protects against database administrators, stolen backups, and most server-side compromise because the keys never reach the DB server. It costs you the ability to query, sort, or index on encrypted values (unless you design for it).
Option B — Server-side encryption surfaced through C#. SQL Server does the encryption (Transparent Data Encryption, Always Encrypted, or column encryption with keys), and your C# code configures or drives it. Protection is against backup theft and at-rest exposure, but a DBA with key access can still decrypt. This keeps data queryable.
If your threat model is "stolen backup or disk," Option B is often sufficient and far cheaper to operate. If your threat model includes "insider DBA" or "compromised database host," only Option A (or Always Encrypted, which is a hybrid) actually holds. Choose deliberately, because migrating later is painful.
Prerequisites Before You Write Any Code
Gather these before starting, or you'll be redoing work.
A target: keys and their lifecycle. Where will the data encryption key live—in a C# app config, Azure Key Vault, AWS KMS, Windows Certificate Store, or SQL Server's own key hierarchy? Decide before coding, since it determines everything downstream. A decision on queryability. Which encrypted columns must be searched, joined, or sorted? Any column you must filter with WHERE equality generally needs deterministic encryption or an indexable scheme; anything you must pattern-match or range-query generally cannot be encrypted in a queryable way at all. SQL Server edition and version. Always Encrypted with secure enclaves requires specific editions and versions; TDE requires Enterprise (or is available in Azure SQL). Confirm against the edition you actually run. .NET version and driver. Always Encrypted requires a modern Microsoft.Data.SqlClient with column encryption enabled. Pin the version. A key rotation plan. Encryption is only as good as your ability to rotate keys without downtime. Sketch it now.
Option 1: Encrypt in C# and Store Ciphertext (The Most Portable Approach)
This is the approach the query most literally asks for: C# code doing encryption, SQL Server just storing the result.
Step 1 — Choose the algorithm and mode correctly
For new work, use AES with an authenticated mode (AES-GCM) if your library supports it, because it gives you confidentiality and tamper detection. If you must use AES-CBC (older .NET APIs), pair it with an HMAC for integrity—never CBC alone. For column values you also want a fresh random IV/nonce per encryption, stored alongside the ciphertext, never reused with the same key in GCM.
Step 2 — Shape the column as binary
Store ciphertext in VARBINARY(MAX) (or a bounded VARBINARY if you know the maximum). Base64-encoding into NVARCHAR is possible but wastes space and invites collation/encoding bugs. Binary is cleaner.
Step 3 — Encrypt in C# before the write
The encryptor wraps a plaintext plus a per-record salt into a single blob: nonce, tag, ciphertext. The key comes from your key store, not a hardcoded string.
Step 4 — For searchable fields, add a deterministic hash column
You can't WHERE on salted randomized ciphertext. To look up by email without decrypting everything, store a keyed hash (HMAC) of the normalized value in a separate column and index that. The hash is deterministic for equality searches only—it gives no ordering and resists precomputation only if the key is secret. Accept the trade-off: an attacker with both the hash and the HMAC key can test guesses.
Step 5 — Decrypt in C# on read, with a check
Read the blob, split off nonce and tag, and decrypt. Authentication failure (GCM tag mismatch) should raise a real error, not silently return garbage—that's your tamper signal.
Success check: insert a row through the C# path, confirm the column contains bytes that don't read as text in SSMS, and that a round-trip decrypt returns the original string. Then flip one byte in a test copy and confirm decryption throws—that verifies integrity detection works.
Where this breaks: you cannot do LIKE, range filters, or ORDER BY on the encrypted column. Reports that join on encrypted keys require decrypting in the application, which can be slow at scale. Plan for a read model or analytics copy if you need heavy querying.
Option 2: Always Encrypted (Client-Side Keys, Server-Side Storage)
Always Encrypted is the closest thing to "C# encryption built into SQL Server." The driver encrypts and decrypts in your C# client; SQL Server stores ciphertext and never sees the keys. That distinction matters: it is not the server doing crypto, it's your application—but the database manages column metadata and enforces the scheme.
Step 1 — Provision a Column Master Key and Column Encryption Key
In SSMS or via T-SQL, define a Column Master Key (CMK) pointing to a certificate or Key Vault key, then a Column Encryption Key (CEK) encrypted by it. The CEK is what actually encrypts columns, and it's stored encrypted by the CMK.
Step 2 — Declare columns as encrypted with a chosen type
Always Encrypted offers two determinism modes. Deterministic allows equality joins and WHERE on the column (same plaintext → same ciphertext) but leaks equality patterns. Randomized hides everything but blocks most predicates. Pick per column based on whether it's a lookup key or just data.
Step 3 — Enable column encryption in the connection string
In C# you add Column Encryption Setting=Enabled to the connection string and use Microsoft.Data.SqlClient. The driver handles encryption transparently; your queries look normal, but only clients with key access can see plaintext.
Success check: run the same SELECT from SSMS without the encryption setting—you should see ciphertext—then from your C# client with keys—plaintext. That gap is the feature working.
Limits: deterministic columns leak frequency patterns; randomized columns can't be filtered or indexed usefully. Always Encrypted with secure enclaves (hardware-backed server-side computation) extends what's queryable but requires specific edition, attestation infrastructure, and isn't universally available. Confirm your edition supports enclaves before designing around them.
Option 3: TDE and Column-Level Keys in SQL Server
If you only need at-rest protection and queryability matters more than DBA-resistance, SQL Server's native features do the work and your C# code just configures them.
Transparent Data Encryption encrypts the entire database and backups at rest with a Database Encryption Key protected by a server certificate. It's essentially a checkbox and requires no schema changes or C# changes beyond enabling it. It does not protect against a DBA querying plaintext—the server decrypts transparently.
ENCRYPTBYKEY / ENCRYPTBYCERT let a stored procedure or query encrypt individual values server-side using SQL Server's key hierarchy. Your C# can call EXEC on those procedures. This keeps data queryable and integrates cleanly, but the keys live in the database server, so anyone with sysadmin can decrypt.
The honest framing: these are operations and compliance controls (they satisfy "data encrypted at rest" requirements), not defenses against a determined insider. Many regulations accept them; few serious threat models treat them as sufficient alone.
Keeping Keys Out of Source and Out of the Database
The single biggest real-world failure isn't the algorithm—it's key handling. Whatever option you choose:
Never hardcode keys. No literals in C#, no plaintext in appsettings.json committed to git. Pull from a secrets manager or the Windows Certificate Store. Separate key custody from data custody. If the key and the ciphertext sit in the same backup, the encryption bought you little. Store keys in Key Vault or KMS with distinct access control so a stolen DB backup alone is useless. Rotate on a schedule and after any suspected exposure. For Option 1, rotation means re-encrypting rows (or versioning keys with a key ID prefix in the blob and decrypting with the matching key). For Always Encrypted, rotate the CEK and re-encrypt columns; the CMK can be rotated without touching data if the CEK stays. Version your ciphertext. Prefix each blob with a scheme/key version byte so you can migrate formats without guessing which key decrypts which row.
Stop condition: if your key store and your database backups share an access boundary—same cloud account, same admin—you have a design problem, not a code problem. Fix the boundary before shipping.
Migrating Existing Plaintext Columns
You can't flip a plaintext column to encrypted in place without a plan.
1: Add new VARBINARY columns alongside the old ones. 2: Backfill in batches: read a chunk, encrypt in C# (Option 1) or via an always-encrypted client (Option 2), write the new column, record progress. 3: Dual-write during cutover so neither old nor new writes are lost. 4: Verify round-trip decryption on a sample, and reconcile row counts. 5: Drop the plaintext column only after a full backup and a cooling-off period.
Do this during a maintenance window if the table is hot, and test the backfill rate on a staging copy first—batch encryption of millions of rows can take hours and will hammer CPU.
Performance, Indexing, and What Breaks at Scale
Encryption has costs you should size before committing.
Storage: AES output plus nonce and tag roughly adds 28 bytes per value (GCM) or 16 (CBC), plus per-row overhead. On a billion small rows that's tens of gigabytes of new data. Query TCP: randomized encryption kills index seeks. Always Encrypted deterministic columns can be indexed, but the server can't do range scans. Your query plans change; retune. CPU: AES is cheap per operation but not free across high-throughput write paths. Measure on realistic volume—don't assume. Joins: joining two encrypted columns works only if both use deterministic (or keyed-hash) schemes; randomized joins are impossible server-side.
If your application needs to filter, sort, and aggregate on sensitive data frequently, encryption fights you constantly. Often the pragmatic answer is to encrypt the truly sensitive fields (identifiers, contact info, credentials) and leave low-sensitivity analytics columns in plaintext—or to keep a segregated, tightly-controlled analytics store.
Common Mistakes and How to Spot Them
Reusing IVs. A fixed IV in GCM catastrophically breaks security. Symptom: encryption "works" but identical plaintexts produce identical ciphertexts—a red flag. Verify fresh nonces on every call. Storing the key next to the data. Ciphertext and key in the same row or same config file. The encryption is theater. Decrypting row-by-row in a loop for a report. Works in test, times out in production. Batch decrypt or add a read model. Forgetting to handle NULL and empty strings in your C# encryptor—either both should round-trip or both should be rejected, not one crashes. No authentication on CBC. CBC alone is malleable; pair it with HMAC or move to GCM.
Verification habit: after any encryption change, write a test that encrypts, stores, retrieves, and decrypts a known value, and one that confirms a tampered blob fails. Those two tests catch most regressions.
FAQ
Can I compile my C# encryption logic and deploy it as a SQL Server CLR assembly?
SQL CLR exists, but it's restricted and poorly suited to modern crypto. Hosting custom assemblies that handle keys inside the database engine is exactly the boundary you're trying to avoid, and CLR is not where you want your key material. Keep encryption in the application tier.
Is Always Encrypted the same as encrypting in C#?
Functionally similar for storage secrecy—keys stay client-side—but Always Encrypted is a supported, driver-managed scheme with SQL metadata, whereas hand-rolled Option 1 code gives you more control and more migration burden. Both keep keys out of SQL Server; neither protects against a fully compromised client.
Does TDE satisfy "encryption at rest" audits?
Usually yes, for at-rest and backup requirements. It does not hide data from a DBA with access. Confirm what the specific regulation demands before relying on it.
How do I search encrypted data?
Only deterministic encryption (or a keyed HMAC column) supports equality lookups. Pattern matching, ranges, and fuzzy search generally can't be done over randomized ciphertext—design your data model around that limit rather than fighting it later.