Knowing the SQL is not enough: a database also has to keep its secrets, and tell you who touched them. This guide shows the basics: HASHBYTES for passwords, ENCRYPTBYPASSPHRASE for values you must read back, dynamic data masking, TDE (transparent data encryption) and SQL Server Audit.
Part of the SQL Server for Beginners series. This article is the written version of lesson 15 of the Bigland Network video course, with the same sample data. All examples were run in SQL Server Management Studio on a test instance (TDE on a throwaway test database). Run every example on a test server, not on production.
Watch lesson 15 as a video or open it on YouTube. The written lesson below follows the same steps and the same sample data.
Contents
- 1. Protect data in layers
- 2. Hash or encrypt?
- 3. ENCRYPTBYPASSPHRASE
- 4. Dynamic data masking
- 5. TDE
- 6. SQL Server Audit
- 7. Mistakes and best practices
- 8. Practice
1. Protect data in layers
- In transit: TLS encrypts the connection.
- At rest: TDE encrypts the files and the backups.
- In columns: hash, encrypt or mask sensitive values.
- Who touched what: auditing, to see the access.
No single layer is enough: each one stops a different problem.
2. Hash or encrypt?
A hash is one way: you cannot go back, and the same input always gives the same output. It is the right tool for passwords: to check a login, hash what the user typed and compare the two hashes. Encryption is two ways: a key opens it, so you can read the value again.
SELECT HASHBYTES('SHA2_256', N'Secret123') AS hash,
LEN(HASHBYTES('SHA2_256', N'Secret123')) AS bytes;
| hash | bytes |
|---|---|
| 0x97876B250CD9136B8D2FF2AE5E1C9ED32772AE940FD7A44CF9ED7D58FA030B37 | 32 |
SHA2_256 always gives 32 bytes. Avoid the old algorithms MD5 and SHA1. To check a password, compare two hashes:
SELECT CASE WHEN HASHBYTES('SHA2_256', N'Secret123')
= HASHBYTES('SHA2_256', N'Secret123')
THEN 'match' ELSE 'no' END AS same_password,
CASE WHEN HASHBYTES('SHA2_256', N'secret123')
= HASHBYTES('SHA2_256', N'Secret123')
THEN 'match' ELSE 'no' END AS other_case;
| same_password | other_case |
|---|---|
| match | no |
One changed letter gives a completely different hash. In a real system, store the hash (with a salt) in the table and compare hashes at login.
3. ENCRYPTBYPASSPHRASE
DECLARE @e VARBINARY(256) =
ENCRYPTBYPASSPHRASE(N'MyPass', N'4111-1111');
SELECT @e AS encrypted,
CONVERT(NVARCHAR(50),
DECRYPTBYPASSPHRASE(N'MyPass', @e)) AS good_pass,
CONVERT(NVARCHAR(50),
DECRYPTBYPASSPHRASE(N'Wrong', @e)) AS wrong_pass;
| encrypted | good_pass | wrong_pass |
|---|---|---|
| 0x0200… (binary, shortened) | 4111-1111 | NULL |
Store the result in a VARBINARY column. A wrong passphrase gives NULL, not an error. Never write the real passphrase in your code.
4. Dynamic data masking
The data stays as it is, but some users see a masked version. Functions: default(), email(), partial() and random(). Sysadmin, db_owner and users with the UNMASK permission see the real values. It is not encryption: it only hides values in query results.
CREATE TABLE dbo.Customers (
Id INT PRIMARY KEY,
FullName NVARCHAR(50),
Email NVARCHAR(100) MASKED WITH (FUNCTION = 'email()'),
Phone VARCHAR(15) MASKED WITH
(FUNCTION = 'partial(0,"XXX-XXX-",4)'),
CardLimit INT MASKED WITH (FUNCTION = 'default()'));
INSERT dbo.Customers VALUES
(1, N'Amina Benali', 'amina@example.com', '0612345678', 5000),
(2, N'Youssef Idrissi', 'youssef@example.com', '0698765432', 3000);
SELECT Email, Phone, CardLimit FROM dbo.Customers;
For a user who only has SELECT (tested with a user created WITHOUT LOGIN and EXECUTE AS):
| Phone | CardLimit | |
|---|---|---|
| aXXX@XXXX.com | XXX-XXX-5678 | 0 |
| yXXX@XXXX.com | XXX-XXX-5432 | 0 |
An administrator, or a user after GRANT UNMASK TO ReportUser;, sees amina@example.com, 0612345678 and 5000. A mask is a curtain, not a safe: users can still guess values by filtering.
5. TDE: Transparent Data Encryption
TDE encrypts the data files, the log files and the backups on disk, with no change in queries or applications. It protects against stolen files or backups, not against a user who has SELECT. It is available in Enterprise and Developer, and in Standard from SQL Server 2019.
USE master;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = N'UseAStrongPassword!1';
CREATE CERTIFICATE TdeCert WITH SUBJECT = N'TDE certificate';
USE BiglandDemo;
CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM = AES_256
ENCRYPTION BY SERVER CERTIFICATE TdeCert;
ALTER DATABASE BiglandDemo SET ENCRYPTION ON;
SELECT name, is_encrypted FROM sys.databases
WHERE name = N'BiglandDemo'; -- 1 when encrypted
Back up the certificate and its key right away. Without them, encrypted backups cannot be restored on another server. Encryption runs in the background, so a big database takes time.
6. SQL Server Audit: who touched what?
Triggers (lesson 10) copy changes into an audit table, which is good for one table. SQL Server Audit is built in and writes events to a file or the event log. It has a server audit (the destination), an audit specification (what to watch) and a function to read the file.
USE master;
CREATE SERVER AUDIT BiglandAudit
TO FILE (FILEPATH = N'C:\SQLAudit\');
ALTER SERVER AUDIT BiglandAudit WITH (STATE = ON);
USE BiglandDemo;
CREATE DATABASE AUDIT SPECIFICATION EmployeesAudit
FOR SERVER AUDIT BiglandAudit
ADD (SELECT, UPDATE ON dbo.Employees BY public)
WITH (STATE = ON);
SELECT action_id, succeeded, object_name
FROM sys.fn_get_audit_file(
N'C:\SQLAudit\*.sqlaudit', DEFAULT, DEFAULT)
WHERE object_name = N'Employees';
The folder must exist, and the SQL Server service account must be able to write to it. After one SELECT and one UPDATE on Employees, the test in Management Studio showed four events:
| action_id | succeeded | object_name |
|---|---|---|
| SL | 1 | Employees |
| SL | 1 | Employees |
| SL | 1 | Employees |
| UP | 1 | Employees |
SL lines are reads of the table and UP is the UPDATE (an UPDATE with a WHERE clause also reads rows, so more than one SL line appears). The real file also has the time and the login name of each event. BY public means every user; name a user or role to audit one person.
7. Mistakes and best practices
- Encrypting passwords when you should hash them.
- Thinking masking is security: it only hides values.
- Turning on TDE and losing the certificate.
- Auditing everything, so nobody reads the log.
- Writing the passphrase inside the code.
- Best practice: hash passwords with SHA2_256 and a salt, back up TDE certificates and keys in a safe place, grant the least permission even with masking, audit sensitive tables and read the audit on a schedule (for example with an Agent job from lesson 14), and keep keys away from the data.
8. Practice
- To check a login password, do you hash it or encrypt it? Which function?
- Mask the Salary column of Employees, so other users see 0.
- Write a query on the audit file that shows only the UPDATE events.
-- 1: hash it, and compare with the stored hash
SELECT HASHBYTES('SHA2_256', N'Secret123');
-- 2: mask Salary
ALTER TABLE dbo.Employees
ALTER COLUMN Salary ADD MASKED WITH (FUNCTION = 'default()');
-- 3: only the UPDATE events
SELECT event_time, server_principal_name, statement
FROM sys.fn_get_audit_file(
N'C:\SQLAudit\*.sqlaudit', DEFAULT, DEFAULT)
WHERE action_id = 'UP';
Frequently asked questions
Should I hash or encrypt passwords in SQL Server?
Hash them, with a modern algorithm such as SHA2_256 and a salt. A hash cannot be reversed, so a leaked table does not simply reveal the passwords. Encrypt only the data you must read back.
Is dynamic data masking real security?
No. It hides values in query results for users without the UNMASK permission, but the data is stored in clear and can be guessed by filtering. Use it with permissions, not instead of them.
What happens if I lose the TDE certificate?
You cannot restore the encrypted backups on another server. Back up the certificate and its private key right after creating them, and store them away from the backups.
What to learn next
The next lesson, Lesson 16: Working with JSON, covers working with JSON: FOR JSON, OPENJSON and JSON_VALUE. Previous lesson: Lesson 14: SQL Server Agent Jobs and Maintenance.
The whole series
- Lesson 1: SELECT, WHERE and ORDER BY
- Lesson 2: JOINs
- Lesson 3: GROUP BY, HAVING and Subqueries
- Lesson 4: INSERT, UPDATE, DELETE and Transactions
- Lesson 5: CREATE TABLE, Data Types and Constraints
- Lesson 6: Indexes, Views and Stored Procedures
- Lesson 7: CTEs and Window Functions
- Lesson 8: Built-in Functions
- Lesson 9: Functions, Temp Tables and Table Variables
- Lesson 10: Triggers and Audit Tables
- Lesson 11: Security: Logins, Users and Roles
- Lesson 12: Backup, Restore and Recovery Models
- Lesson 13: Query Performance Tuning
- Lesson 14: SQL Server Agent Jobs and Maintenance
- Lesson 15: Encryption and Auditing Basics (this article)
- Lesson 16: Working with JSON
- Lesson 17: Temporal Tables and Row History
- Lesson 18: Partitioning and Large Tables
- lesson 19: Full Text Search
- lesson 20: Query Store and Slow Queries
Sources and further reading
- Microsoft Learn, Transact-SQL reference (Database Engine), on learn.microsoft.com: the official syntax for the statements used here.
- Microsoft Learn, HASHBYTES, Dynamic Data Masking, Transparent Data Encryption and SQL Server Audit, for the full details of each feature.
More tutorials like this
Msg 208 Invalid Object Name in SQL Server: Causes and Fix
Fix SQL Server Msg 208 Invalid object name: check the spelling, the database and the schema, with real SSMS examples and scripts to find…
SQL Server Query Store Tutorial: Find Slow Queries, Compare Plans and Force a Plan
Turn on Query Store, find the most expensive queries with the sys.query_store views and the SSMS reports, compare the plans of one query and…
SQL Server Full Text Search Tutorial: CONTAINS, FORMSOF and CONTAINSTABLE
Search words inside text columns fast: create a full text catalog and index, use CONTAINS, word forms, phrases and rank the best matches with…
