- SQL Server 2008 - How to Encrypt Your Data Using Transparent Data Encryption (TDE)
- SQL Server 2016 - How to Encrypt Your Data Using Always Encrypted
- SQL Server 2016 - Data Masking with Dynamic Data Masking (DDM)
- General Personal Data Protection Act (LGPDP or LGPD) applied to SQL Server databases
Ready for one more article?
With the advent of GDPR, business data security concerns are growing, and an area that was once overlooked is in evidence more than ever now. As a result, IT professionals, especially DBAs, have been looking for ways to reduce the risk of data exposure and one way to do this is to encrypt data to prevent unauthorized access by third parties.
My idea in this article is to demonstrate a SQL Server solution that lets you encrypt data, which is the Always Encrypted, available from SQL Server 2016 on Express, Standard, Enterprise, and Developer editions (Express and Standard from 2016 SP1).
Be sure to check out my post SQL Server 2008 - How to Encrypt Your Data Using Transparent Data Encryption (TDE), another SQL Server data encryption solution.
For the examples below, I will use the following script for base generation:
IF (OBJECT_ID('dbo.Pessoa') IS NOT NULL) DROP TABLE dbo.Pessoa
CREATE TABLE dbo.Pessoa
INSERT INTO dbo.Pessoa
( N'Jon Yang', N'1971-10-06T00:00:00', N'[email protected]', N'1 (11) 500 555-0162' ),
( N'Eugene Huang', N'1976-05-10T00:00:00', N'[email protected]', N'1 (11) 500 555-0110' ),
( N'Ruben Torres', N'1971-02-09T00:00:00', N'[email protected]', N'1 (11) 500 555-0184' ),
( N'Christy Zhu', N'1973-08-14T00:00:00', N'[email protected]', N'1 (11) 500 555-0162' ),
( N'Elizabeth Johnson', N'1979-08-05T00:00:00', N'[email protected]', N'1 (11) 500 555-0131' ),
( N'Julio Ruiz', N'1976-08-01T00:00:00', N'[email protected]', N'1 (11) 500 555-0151' ),
( N'Janet Alvarez', N'1976-12-02T00:00:00', N'[email protected]', N'1 (11) 500 555-0184' ),
( N'Marco Mehta', N'1969-11-06T00:00:00', N'[email protected]', N'1 (11) 500 555-0126' ),
( N'Rob Verhoff', N'1975-07-04T00:00:00', N'[email protected]', N'1 (11) 500 555-0164' ),
( N'Shannon Carlson', N'1969-09-29T00:00:00', N'[email protected]', N'1 (11) 500 555-0110' ),
( N'Jacquelyn Suarez', N'1969-08-05T00:00:00', N'[email protected]', N'1 (11) 500 555-0169' ),
( N'Curtis Lu', N'1969-05-03T00:00:00', N'[email protected]', N'1 (11) 500 555-0117' ),
( N'Lauren Walker', N'1979-01-14T00:00:00', N'[email protected]', N'717-555-0164' ),
( N'Ian Jenkins', N'1979-08-03T00:00:00', N'[email protected]', N'817-555-0185' ),
( N'Sydney Bennett', N'1973-11-06T00:00:00', N'[email protected]', N'431-555-0156' ),
( N'Chloe Young', N'1984-08-26T00:00:00', N'[email protected]', N'208-555-0142' ),
( N'Wyatt Hill', N'1984-10-25T00:00:00', N'[email protected]', N'135-555-0171' ),
( N'Shannon Wang', N'1949-12-24T00:00:00', N'[email protected]', N'1 (11) 500 555-0195' ),
( N'Clarence Rai', N'1955-10-06T00:00:00', N'[email protected]', N'1 (11) 500 555-0137' ),
( N'Luke Lal', N'1983-09-04T00:00:00', N'[email protected]', N'262-555-0112' )
What is Always Encrypted
Always Encrypted is a feature designed to protect sensitive data, available from SQL Server 2016, such as credit card or national identification numbers (for example, US social security numbers) stored in Bank of America databases. Azure SQL data or SQL Server. Always Encrypted allows customers to encrypt sensitive data in client applications and never reveal encryption keys to the Database Engine. As a result, Always Encrypted provides a separation between those who own the data (and can display it) and those who manage the data (but should not have access).
One of the biggest advantages of Always Encrypted is that only users and applications that have the master encryption key have access to the original data. Not even DBAs and other sysadmin users can view the original data. This ensures data and information security at a level rarely seen in other solutions. Another great advantage of this solution is that the data is encrypted, as well as the logs, backups, and data trafficked across the network, ensuring complete security on all media, even if someone intercepts packets during their transmission. Because of this, losing the master key can be fatal to your data because recovering it is no longer possible since a backup made to an Always Encrypted database can only be restored to another instance if the master key be restored before.
Always Encrypted makes encryption almost transparent to applications. An Always Encrypted-enabled driver installed on the client computer accomplishes this by automatically encrypting and decrypting sensitive data in the client application. The driver encrypts sensitive data columns before passing data to the Database Engine and automatically reconfigures queries so that application semantics are preserved. Similarly, the driver transparently decrypts data stored in encrypted database columns that is contained in the query results.
However, while this feature ensures an excellent level of security, be aware of potential performance issues when using it and increasing space consumption:
Always Encrypted vs Transparent Data Encryption (TDE)
Below, I will list some similarities and differences between these two SQL Server encryption solutions:
|Always Encrypted||Transparent Data Encryption (TDE)|
|Column level||Database Level|
|Client Encryption (using a driver)||Server Encryption (Database Engine)|
|Server does not know encryption keys||Server knows encryption keys|
|Data in memory is encrypted||Data in memory is unprotected (plain-text)|
|Data on the network is encrypted||Data on the network is unprotected (plain-text)|
|Only users with key access can view the original data. Not even the DBA can view the original data without the key.||DBA can view original data without key|
|Backups and log files are encrypted||Backups and log files are encrypted|
|Requires application changes (may be small or large depending on the encryption algorithm you choose)||No app changes required|
|Available from SQL Server 2016 - All editions, up to Express (Express and Standard from 2016 SP1)||Available from SQL Server 2008 - Enterprise and Developer Only|
Deterministic or Random Encryption
When using Always Encrypted, you will find that there are 2 ways to encrypt columns in this solution:
- Deterministic: Deterministic encryption always generates the same encrypted value for the same text. Using deterministic encryption provides lookups, joins, groupings, and indexing on encrypted columns. However, it can also allow unauthorized users to estimate encrypted value information by examining patterns in the encrypted column, especially if there is a small set of possible encrypted values, such as True / False or North / South / East / West region.
- Randomized: Random encryption uses a method that encrypts data in a less predictable manner, ie for the same text the encrypted value is different. Random encryption is more secure, but prevents the use of lookups, collations, indexing, and joins on encrypted columns.
How to install and configure Always Encrypted on SQL Server
Now that I've explained some of the Always Encrypted theory, let's move on to the practical part.
The most practical way to encrypt a column is by using SQL Server Management Studio (SSMS):
And changing existing tables can also be done using PowerShell:
$sqlConnectionString = "Data Source=sqlserver\sql2017;Initial Catalog=AdventureWorksDW;User ID=dirceu.resende;MultipleActiveResultSets=False;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;Packet Size=4096;Application Name=`"Microsoft SQL Server Management Studio`""
$smoDatabase = Get-SqlDatabase -ConnectionString $sqlConnectionString
# If your encryption changes involve keys in Azure Key Vault, uncomment one of the lines below in order to authenticate:
# * Prompt for a username and password:
# * Enter a Client ID, Secret, and Tenant ID:
#Add-SqlAzureAuthenticationContext -ClientID '<Client ID>' -Secret '<Secret>' -Tenant '<Tenant ID>'
$encryptionChanges = @()
# Add changes for table [dbo].[Pessoa]
$encryptionChanges += New-SqlColumnEncryptionSettings -ColumnName dbo.Pessoa.Name -EncryptionType Randomized -EncryptionKey "CEK_Auto1"
$encryptionChanges += New-SqlColumnEncryptionSettings -ColumnName dbo.Pessoa.BirthDate -EncryptionType Deterministic -EncryptionKey "CEK_Auto1"
$encryptionChanges += New-SqlColumnEncryptionSettings -ColumnName dbo.Pessoa.EmailAddress -EncryptionType Randomized -EncryptionKey "CEK_Auto1"
$encryptionChanges += New-SqlColumnEncryptionSettings -ColumnName dbo.Pessoa.Phone -EncryptionType Randomized -EncryptionKey "CEK_Auto1"
Set-SqlColumnEncryption -ColumnEncryptionSettings $encryptionChanges -InputObject $smoDatabase
However, it is not possible to encrypt existing table columns using Transact-SQL, just create a new encrypted table (you can create a new encrypted table and migrate data from the previous table), which would have this syntax:
CREATE COLUMN MASTER KEY [CMK_Auto1]
KEY_STORE_PROVIDER_NAME = N'MSSQL_CERTIFICATE_STORE',
KEY_PATH = N'CurrentUser/my/D8CDCC7BC22069DEC1FCF32A5C349FCD33424FAA'
CREATE COLUMN ENCRYPTION KEY [CEK_Auto1]
COLUMN_MASTER_KEY = [CMK_Auto1],
ALGORITHM = 'RSA_OAEP',
CREATE TABLE [dbo].[Pessoa](
[Name] [NVARCHAR](101) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL,
[BirthDate] [DATE] ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = DETERMINISTIC, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL,
[EmailAddress] [NVARCHAR](50) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL,
[Phone] [NVARCHAR](20) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [CEK_Auto1], ENCRYPTION_TYPE = RANDOMIZED, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL
Viewing Always Encrypted Data in SQL Server
Remember that the user can only see the original data if they have VIEW ANY COLUMN MASTER KEY DEFINITION and VIEW ANY COLUMN ENCRYPTION KEY DEFINITION permissions or if you are storing Master Encryption Key and Column Encryption Key on the bank server (Windows Certification Store) and the certificate is stored on your machine or on your user. If you want to use a safer way, opt for Azure Key Vault (AKV).
To help set up Always Encrypted in your applications, I've separated more 2 articles that can help DEVs configure this feature with Azure Key Vault (AKV):
How to identify which columns are encrypted with Always Encrypted
To identify which columns are encrypted with Always Encrypted and which encryption algorithm is used, simply use the query below:
DB_NAME() AS [database],
t.[name] AS [table],
c.[name] AS [column],
JOIN sys.tables t ON t.[object_id] = c.[object_id]
c.encryption_algorithm_name IS NOT NULL
Always Encrypted Restrictions
Always Encrypted columns are not supported for the columns below (for example, the Encrypted WITH clause cannot be used in a column's CREATE TABLE / ALTER TABLE if one of the following conditions applies to the column):
- Columns using one of the following data types: xml, timestamp / rowversion, image, ntext, text, sql_variant, hierarchyid, geography, geometry, alias, and user-defined types.
- FILESTREAM columns
- Columns with the IDENTITY property
- Columns with the ROWGUIDCOL property.
- String columns (varchar, char, etc.) with non-bin2 collations
- Columns that are keys to nonclustered indexes using a randomly encrypted column as a key column (deterministically encrypted columns are allowed)
- Columns that are keys to clustered indexes using a randomly encrypted column as a key column (deterministically encrypted columns are allowed)
- Columns that are keys to fulltext indexes containing random, deterministic, encrypted columns
- Columns referenced by computed columns (when the expression performs operations not supported by Always Encrypted)
- Sparse Column Set
- Columns that are referenced by statistics
- Columns using alias type
- Partitioning Columns
- Columns with default constraint
- Columns referenced by unique constraints when using random encryption (deterministic encryption supported)
- Primary key columns when using random encryption (deterministic encryption is supported)
- Reference columns in foreign key constraints when using random encryption, or when using deterministic encryption, if the referenced and reference columns use different algorithms or keys.
- Columns referenced by check constraint
- Columns in tables that use Change Data Capture (CDC)
- Primary Key Columns in Change Tracking Tables
- Masked Columns (using Dynamic Data Masking)
- Columns in Stretch Database Tables (Tables with columns encrypted with Always Encrypted can be Stretch enabled.)
- Columns in external tables (PolyBase) (Note: The use of external tables and tables with encrypted columns in the same query is supported)
- Table-valued parameters targeting encrypted columns are not supported.
The following clauses cannot be used for encrypted columns:
- FOR XML
- FOR JSON PATH
The following features do not work on encrypted columns:
- Transactional Replication or Merge Replication
- Distributed Queries (Linked Servers)
Dynamic Data Masking
After demonstrating the use of this encryption solution, you may be asking, "What about Dynamic Data Masking (DDM) ???". Well, for starters, DDM is not a data encryption solution but a data masking solution.
While data encryption effectively prevents your data from being restored (including from backups) and accessed improperly, data masking with Dynamic Data Masking only restricts content that is displayed at the end of a SELECT command, or that is, if you have access to a backup file, you can restore it to an instance where you are sysadmin and you have free access to previously masked data.
To learn more about Dynamic Data Masking, see the article. SQL Server 2016 - Data Masking with Dynamic Data Masking (DDM), where I demonstrate how to use it, restrictions and even how to “break” masking and access the original data (even without permission).
Well guys, I hope you enjoyed this article and now start protecting your data better!
Big hug and until next time!