数据库加密&证书创建

时间:2024-03-07 20:40:46

以下是用sqlserver给数据库进行加密的脚本,其中当然也包含了证书创建的步骤:

USE master;
GO   
--drop master key
CREATE MASTER KEY ENCRYPTION BY PASSWORD = \'123456\';  
GO

BACKUP MASTER KEY TO FILE = \'D:\SQL1_master.key\' ENCRYPTION BY   
PASSWORD = \'123456\';  
GO    
CREATE CERTIFICATE TDECert WITH SUBJECT = \'TDE Certificate\';  
GO

BACKUP CERTIFICATE TDECert TO FILE = \'D:\SQL1_master.cer\'   
WITH PRIVATE KEY (   
FILE  = \'D:\SQL1_TDECert.pvk\',   
ENCRYPTION BY PASSWORD = \'123456\'   
    );  

USE TEST;   
GO   
CREATE DATABASE ENCRYPTION KEY   
WITH ALGORITHM = AES_128   
ENCRYPTION BY SERVER CERTIFICATE TDECert;

GO
ALTER DATABASE TEST SET ENCRYPTION ON


--如果需要还原加密后的数据库文件到另外一台服务器,需要首先还原证书到目标服务器:
--目标服务器的master key 可以跟原服务器的不一样
USE master;   
CREATE CERTIFICATE TDECert FROM FILE = \'D:\SQL1_master.cer\'   
      WITH PRIVATE KEY (   
        FILE  = \'D:\SQL1_TDECert.pvk\',   
        DECRYPTION BY PASSWORD = \'123456\'   
    );