透明数据加密是SQL Server数据库安全众多特性中的一个,本文只针对透明数据加密。
在此测试之前,已经按照文档如何快速获得一个测试用SQL Server企业版创建了一个SQL Server 2019,并按照文档为SQL Server安装示例数据库AdventureWorks安装了样例数据库并导入了测试数据。
这里的SQL Server虽然是2019,但其他版本的SQL Server也是类似的,SQL Server从2016版开始支持透明数据加密。
操作非常简单,毕竟这是数据库内置的功能:
1> use master;
2> go
Changed database context to 'master'.
1> create master key encryption by password = 'Welcome1';
2> go
1> create certificate MyServerCert with subject = 'My DEK Certificate';
2> go
1> use AdventureWorks2019;
3> go
Changed database context to 'AdventureWorks2019'.
1> CREATE DATABASE ENCRYPTION KEY
2> WITH ALGORITHM = AES_256
3> ENCRYPTION BY SERVER CERTIFICATE MyServerCert;
4> go
Warning: The certificate used for encrypting the database encryption key has not been backed up. You should immediately back up the certificate and the private key associated with the certificate. If the certificate ever becomes unavailable or if you must restore or attach the database on another server, you must have backups of both the certificate and the private key or you will not be able to open the database.
1> ALTER DATABASE AdventureWorks2019 SET ENCRYPTION ON;
2> go
以上的报警是提示你需要备份秘钥,略。
其实SQL Server的加密架构,和Oracle,和MySQL都是一样的。都是两层秘钥架构,即主密钥和加密密钥。
此时查看数据文件,发现都是乱码:
$ sudo strings /var/opt/mssql/data/AdventureWorks2019_Data.mdf|more
Jn9v5
Jn9v
g 4d
|%&z"
Jn9v5
Jn9v
g 4d
|%&z"
Jn9v5
Jn9v
g 4d
|%&z"
Jn9v5
Jn9v
g 4d
|%&z"
Jn9v5
Jn9v
g 4d
...
$ sudo strings /var/opt/mssql/data/AdventureWorks2019_log.ldf |more
Jn9v5
Jn9v
Jn9v
$
Jn9v
Jn9v
g 4d
|%&z"
$
Jn9v
Jn9v
g 4d
|%&z"
...
查询加密状态:
解密:
1> use AdventureWorks2019;
2> go
Changed database context to 'AdventureWorks2019'.
1> alter database AdventureWorks2019 set encryption off;
2> go
解密后,探索数据文件,可以看到明码,包括数据库中存储的源代码:
参考
- SQL Server 2019 透明数据加密
- SQL Server 2022 透明数据加密
- SQL Server 数据库安全
- Database encryption becomes transparent with SQL Server TDE!