TDE的主要做用是防止數據庫備份或數據文件被偷了之後,偷數據庫備份或文件的人在沒有數據加密密鑰的狀況下是沒法恢復或附加數據庫的。數據庫
USE [master];
GO
--查看master數據庫是否被加密
SELECT name,is_master_key_encrypted_by_server FROM
sys.databases;
--建立master數據庫下的主數據庫密鑰
CREATE MASTER KEY ENCRYPTION BY PASSWORD = N'^&*()0A';
--查看master數據庫下的密鑰信息
SELECT * FROM sys.symmetric_keys;
--建立證書用來保護 數據庫加密密鑰 (DEK)
CREATE CERTIFICATE master_server_cert WITH
SUBJECT = N'Master Protect DEK Certificate';
IF DB_ID('db_encryption_test') IS NOT NULL
DROP DATABASE db_encryption_test
--建立測試數據庫
CREATE DATABASE db_encryption_test;
GO
USE db_encryption_test;
--建立由master_server_cert保護的DEK 數據庫加密密鑰 (對稱密鑰)
CREATE DATABASE ENCRYPTION KEY
WITH ALGORITHM = AES_128
ENCRYPTION BY SERVER CERTIFICATE master_server_cert;
GO測試
USE master;
BACKUP CERTIFICATE master_server_cert TO FILE = 'D:\MSSQL\Certificate\master_server_cert.cer'
WITH PRIVATE KEY (
FILE = 'D:\MSSQL\Certificate\master_server_cert.pvk' ,
ENCRYPTION BY PASSWORD = '^&*()0A';
--相應的,咱們也備份一下數據庫主密鑰(master)
USE master;
--若是沒有啓用主密鑰的自動解密功能
--OPEN MASTER KEY DECRYPTION BY PASSWORD = '^&*()0A';
BACKUP MASTER KEY TO FILE = 'D:\MSSQL\MasterKey\master.cer'
ENCRYPTION BY PASSWORD = '^&*()0A';
GO
--生產環境下,設置成單用戶在運行加密
ALTER DATABASE db_encryption_test SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
--備份成功之後,開啓TDE 加密
ALTER DATABASE db_encryption_test SET ENCRYPTION ON;
GO
--設置多用戶訪問
ALTER DATABASE db_encryption_test SET MULTI_USER WITH ROLLBACK IMMEDIATE;
GO
--查看db_encryption_test數據庫是否被加密 encryption_state:3 TDE加密了
SELECT DB_NAME(database_id),encryption_state FROM sys.dm_database_encryption_keys;
/*
發現tempdb也被加密了。MSDN解釋是:若是實例中有一個數據庫啓用了TDE加密,那麼tempdb也被加密
*/
--接下來,找另一臺機器或者實例來測試,若是數據文件被盜走了,防止附加的測試.
USE master;
EXEC sp_detach_db N'db_encryption_test';
GO
USE master;
--我先在他機器還原了MASTER KEY (他原機器master庫無master key)
RESTORE MASTER KEY
FROM FILE = 'C:\Users\Administrator\Desktop\master.cer'
DECRYPTION BY PASSWORD = '^&*()0A'
ENCRYPTION BY PASSWORD = '^&*()0A';
GO
--若是沒有自動加密
OPEN MASTER KEY DECRYPTION BY PASSWORD=N'^&*()0A';
--建立證書
CREATE CERTIFICATE master_server_cert
FROM FILE = 'C:\Users\Administrator\Desktop\master_server_cert.cer'
WITH PRIVATE KEY (FILE = 'C:\Users\Administrator\Desktop\master_server_cert.pvk',
DECRYPTION BY PASSWORD = '^&*()0A';
GO
--附加數據庫
CREATE DATABASE db_encryption_test
ON PRIMARY
(
FILENAME=N'C:\Users\Administrator\Desktop\db_encryption_test.mdf'
)
LOG ON
(
FILENAME=N'C:\Users\Administrator\Desktop\db_encryption_test_log.ldf'
)
FOR ATTACH ;
GO
--測試成功
--關閉數據庫聯接
CLOSE MASTER KEY加密