SQLServer Always Encrypted with SSMS and C#
Always Encrypted lets SQL Server store sensitive column values as cipher text while an authorized application reads the original values. The client driver uses a column master key (CMK) to unlock the column encryption key (CEK), which it uses to decrypt the results. In this walkthrough, we’ll encrypt [col1] in [dbo].[DEKSampledata], read it from a C# app and then convert the stored column back to plaintext.
Prepare the demo table
Run this script in a test database if you need a fresh copy of the table. If [dbo].[DEKSampledata] already exists, skip the setup and use your existingrows. The demo treats [col1] as nullable Unicode text. Its binary collationsupports deterministic Always Encrypted on a character column.
IF OBJECT_ID(N'dbo.DEKSampledata', N'U') IS NULLBEGIN CREATE TABLE [dbo].[DEKSampledata] ( [id] int NOT NULL PRIMARY KEY, [col1] nvarchar(100) COLLATELatin1_General_100_BIN2 NULL ); INSERT INTO [dbo].[DEKSampledata]([id], [col1]) VALUES (1, N'Demo value one'), (2,N'Demo value two');END;
Encryptcol1 in SSMS
In Object Explorer, expand your database and Tables. Right-click [dbo].[DEKSampledata]and open Always Encrypted Wizard. Some SSMS versions label the action EncryptColumns.
Select [col1] and set Encryption Type to Deterministic. For a fresh demo, select a new columnencryption key so the wizard can create one, and choose the Windows CertificateStore when prompted for the master key location. To reproduce the existing setup,select CEK_Auto1 if it already exists and you can use its master key.
Choose to run the operation now, review the summary and select Finish. Confirm success on the results page. Deterministic encryption allows equality lookups with parameters. It also produces the same ciphertext for repeated values under the same key, whichcan reveal patterns.
Run the querybelow in an ordinary SSMS connection to see cipher text. Then reconnect using Connect to Server > Options > Always Encrypted, enable column encryptionand run the same query in a new window on that connection. With access to themaster key, SSMS displays the original text.
SELECT [id], [col1]FROM [dbo].[DEKSampledata]ORDER BY [id];
Build a C# connection screen
This Windows console demo prompts for a SQL Server instance and database, connects using thecurrent Windows identity and reads the same table. Create a .NET consoleproject and add the SQL Server driver.
dotnet new console -n ColumnEncryptionDemocd Column EncryptionDemodotnet add package Microsoft.Data.SqlClient
Replace Program.cs with the following code. Use a server name that matches the SQL Server TLS certificate and make sure the client trusts its issuer.
using System;using Microsoft.Data.SqlClient;Console.Write("SQL Server instance: ");var server = Console.ReadLine()?.Trim();Console.Write("Database: ");var database = Console.ReadLine()?.Trim();if (string.IsNullOrWhiteSpace(server) || string.IsNullOrWhiteSpace(database)){ Console.Error.WriteLine("Enter aserver and database."); return;}var settings = new SqlConnectionStringBuilder{ DataSource = server, InitialCatalog = database, IntegratedSecurity = true, TrustServerCertificate = false, ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Enabled};settings["Encrypt"] = "True";using var connection = new SqlConnection(settings.ConnectionString);using var command = new SqlCommand( "SELECT [id], [col1] FROM[dbo].[DEKSampledata] ORDER BY [id];", connection);connection.Open();using var reader = command.ExecuteReader();int idColumn = reader.GetOrdinal("id");int textColumn = reader.GetOrdinal("col1");while (reader.Read()){ string value =reader.IsDBNull(textColumn) ? "(null)" : reader.GetString(textColumn); Console.WriteLine($"{reader.GetInt32(idColumn)}: {value}");}
Run dotnet run and enter the server and database. With the demo rows, the first result is 1: Demo value one. This sample prints synthetic values to show that the driver decrypted them.
The Windows account running the app needs access to the master key's private key. In SSMS,check Database > Security > Always Encrypted Keys > Column Master Keys for the key path. If it starts with CurrentUser/My, the certificate and privatekey must be available in the personal certificate store of the Windows identity running the app. That identity might be a service account in production. The SQL database user also needs SELECT access and permission to read the column master key and column encryption key metadata.
Remove encryption from the stored column
Open the Always Encrypted wizard for [dbo].[DEKSampledata] from an SSMS session that can access the master key.
Select [col1] and change Encryption Type from Deterministic to Plaintext. Run the operationand confirm success. The wizard converts the stored values to plain text. For a production table, plan a maintenance window because the operation can block writes.
Open a new SSMS connection with Always Encrypted disabled and rerun the SELECT. You should now see readable values. Run the following metadata query to confirm that encryption_type_desc is NULL for [col1].
SELECT [name], [encryption_type_desc]FROM sys.columnsWHERE [object_id] = OBJECT_ID(N'dbo.DEKSampledata') AND [name] = N'col1';
Keep the key material available for other columns or older backups that may still depend on it.