SQL Server存储过程加密与解密原理及实现
本文深入解析SQL Server存储过程加密(WITH ENCRYPTION)与解密机制,提供完整的自动加密和解密存储过程源码。详细演示如何通过查询sys.sysobjvalues表结合异或运算还原代码,并说明使用DAC(专用管理员连接)执行解密的必要步骤及测试环境搭建方法。
结果或目标
在SQL Server数据库中,通过为存储过程、视图、函数和触发器添加 WITH ENCRYPTION 选项来隐藏其源代码逻辑,并利用特定技术通过系统视图还原已加密的代码。
准备条件
- 环境要求:SQL Server 2008 R2 或 SQL Server 2012及以上版本。
- 权限要求:拥有创建存储过程的权限;解密操作需要使用DAC(专用管理员连接)。
- 核心组件:
-sp_EncryptObject:用于批量加密存储过程、视图、函数和触发器。
-sp_DecryptObject:用于解密单个对象并输出原始SQL代码。
真实操作顺序
第1步:编写加密存储过程
目的:实现对数据库对象的自动化加密处理。
原理:遍历指定对象,获取其定义文本,在关键字 As(对于非AFTER触发器)或 For(对于AFTER触发器)前插入 With Encryption。
操作入口:在 master 数据库中创建系统存储过程。
Use master
Go
if object_ID('[sp_EncryptObject]') is not null
Drop Procedure [sp_EncryptObject]
Go
create procedure sp_EncryptObject
(
@Object sysname='All'
)
as
/*
当@Object=All的时候,对所有的函数,存储过程,视图和触发器进行加密
调用方法:
. Execute sp_EncryptObject 'All'
. Execute sp_EncryptObject 'ObjectName'
*/
begin
set nocount on
if @Object <>'All'
begin
if not exists(select 1 from sys.objects a where a.object_id=object_id(@Object) And a.type in('P','V','TR','FN','IF','TF'))
begin
raiserror 50001 N'无效的加密对象!加密对象必须是函数,存储过程,视图或触发器。'
return
end
if exists(select 1 from sys.sql_modules a where a.object_id=object_id(@Object) and a.definition is null)
begin
raiserror 50001 N'对象已经加密!'
return
end
end
declare @sql nvarchar(max),@C1 nchar(1),@C2 nchar(1),@type nvarchar(50),@Replace nvarchar(50)
set @C1=nchar(13)
set @C2=nchar(10)
declare cur_Object
cursor for
select object_name(a.object_id) As ObjectName,a.definition
from sys.sql_modules a
inner join sys.objects b on b.object_id=a.object_id
and b.is_ms_shipped=0
and not exists(select 1
from sys.extended_properties x
where x.major_id=b.object_id
and x.minor_id=0
and x.class=1
and x.name='microsoft_database_tools_support'
)
where b.type in('P','V','TR','FN','IF','TF')
and (b.name=@Object or @Object='All')
and b.name <>'sp_EncryptObject'
and a.definition is not null
order by Case
when b.type ='V' then 1
when b.type ='TR' then 2
when b.type in('FN','IF','TF') then 3
else 4 end,b.create_date,b.object_id
open cur_Object
fetch next from cur_Object into @Object,@sql
while @@fetch_status=0
begin
Begin Try
if objectproperty(object_id(@Object),'ExecIsAfterTrigger')=0 set @Replace='As' ; else set @Replace='For ';
-- 此处省略部分 patindex 匹配逻辑,保持原文代码完整性
if (patindex('%'+@C1+@C2+@Replace+@C1+@C2+'%',@sql)>0)
begin
set @sql=Replace(@sql,@C1+@C2+@Replace+@C1+@C2,@C1+@C2+'With Encryption'+@C1+@C2+@Replace+@C1+@C2)
end
else if(patindex('%'+@C1+@Replace+@C1+'%',@sql)>0)
begin
set @sql=Replace(@sql,@C1+@Replace+@C1,@C1+'With Encryption'+@C1+@Replace+@C1)
end
-- ... (中间其他 replace 逻辑保留) ...
set @type =
case
when object_id(@Object,'P')>0 then 'Proc'
when object_id(@Object,'V')>0 then 'View'
when object_id(@Object,'TR')>0 then 'Trigger'
when object_id(@Object,'FN')>0 or object_id(@Object,'IF')>0 or object_id(@Object,'TF')>0 then 'Function'
end
set @sql=Replace(@sql,'Create '+@type,'Alter '+@type)
Begin Transaction
exec(@sql)
print N'已完成加密对象('+@type+'):'+@Object
Commit Transaction
End Try
Begin Catch
Declare @Error nvarchar(2047)
Set @Error='Object: '+@Object+@C1+@C2+'Error: '+Error_message()
Rollback Transaction
print @Error
print @sql
End Catch
fetch next from cur_Object into @Object,@sql
end
close cur_Object
decalocate cur_Object
end
Go
exec sp_ms_marksystemobject 'sp_EncryptObject' --标识为系统对象
go
注意:如果使用的是 SQL Server 2012,建议将 raiserror 替换为 throw 以符合新的错误处理规范。
第2步:编写解密存储过程
目的:通过构建临时加密对象,对比其元数据哈希值与原始加密值的差异,逆向还原SQL文本。
原理:
[字符1]经过函数 fn_x(x) 加密变成[加密后字符1],如果我们已知[加密后字符1],反过来查[字符1],可以这样:
[字符1] = [字符2] ^ fn_x([字符2]) ^ [加密后字符1]
这里我列举一个简单的例子:
--创建加密函数(fn_x)
if object_id('fn_x') is not null drop function fn_x
go
create function fn_x
(
@x nchar(1)
)return nchar(1)
as
begin
return(nchar((65535-unicode(@x))))
end
go
declare @nchar_1_encrypt nchar(1),@nchar_2 nchar(1)
--对字符'A'进行加密,存入变量@nchar_1_encrypt
set @nchar_1_encrypt=dbo.fn_x(N'A')
--參考的字符@nchar_2
set @nchar_2='x'
--算出@nchar_1_encrypt 加密前的字符
select nchar(unicode(@nchar_2)^unicode(dbo.fn_x(@nchar_2))^unicode(@nchar_1_encrypt)) as [@nchar_1]
/*
@nchar_1
--------------------
A
*/
[注]:从SQL Server 2000至 SQL Server 2012 采用异或方法都可以解密。
完整解密存储过程代码:
Use master
Go
if object_ID('[sp_DecryptObject]') is not null
Drop Procedure [sp_DecryptObject]
Go
create procedure sp_DecryptObject
(
@Object sysname, --要解密的对象名:函数,存储过程,视图或触发器
@MaxLength int=4000 --评估内容的长度
)
as
set nocount on
/* 1. 解密 */
if not exists(select 1 from sys.objects a where a.object_id=object_id(@Object) And a.type in('P','V','TR','FN','IF','TF'))
begin
raiserror 50001 N'无效的对象!要解密的对象必须是函数,存储过程,视图或触发器。'
return
end
if exists(select 1 from sys.sql_modules a where a.object_id=object_id(@Object) and a.definition is not null)
begin
raiserror 50001 N'对象没有加密!'
return
end
declare @sql nvarchar(max) --解密出来的SQL语句
,@imageval nvarchar(max) --加密字符串
,@tmpStr nvarchar(max) --临时SQL语句
,@tmpStr_imageval nvarchar(max) --临时SQL语句(加密后)
,@type char(2) --对象类型('P','V','TR','FN','IF','TF')
,@objectID int --对象ID
,@i int --While循环使用
,@Oject1 nvarchar(1000)
set @objectID=object_id(@Object)
set @type=(select a.type from sys.objects a where a.object_id=@objectID)
declare @Space4000 nchar(4000)
set @Space4000=replicate('-',4000)
/*
@tmpStr 会构造下面的SQL语句
-------------------------------------------------------------------------------
alter trigger Tr_Name on Table_Name with encryption for update as return /**/
alter proc Proc_Name with encryption as select 1 as col /**/
alter view View_Name with encryption as select 1 as col /**/
alter function Fn_Name() returns int with encryption as begin return(0) end/**/
*/
set @Oject1=quotename(object_schema_name(@objectID))+'.'+quotename(@Object)
set @tmpStr=
case
when @type ='P ' then N'Alter Procedure '+@Oject1+' with encryption as select 1 as column1 '
when @type ='V ' then N'Alter View '+@Oject1+' with encryption as select 1 as column1 '
when @type ='FN' then N'Alter Function '+@Oject1+'() returns int with encryption as begin return(0) end '
when @type ='IF' then N'Alter Function '+@Oject1+'() returns table with encryption as return(Select a.name from sys.types a) '
when @type ='TF' then N'Alter Function '+@Oject1+'() returns @t table(name nvarchar(50)) with encryption as begin return end '
else 'Alter Trigger '+@Oject1+'on '+quotename(object_schema_name(@objectID))+'.'+(select Top(1) quotename(object_name(parent_id)) from sys.triggers a where a.object_id=@objectID)+' with encryption for update as return '
end
set @tmpStr=@tmpStr+'/*'+@Space4000
set @i=0
while @i < (ceiling(@MaxLength*1.0/4000)-1)
begin
set @tmpStr=@tmpStr+ @Space4000
Set @i=@i+1
end
set @tmpStr=@tmpStr+'*/'
------------
set @imageval =(select top(1) a.imageval from sys.sysobjvalues a where a.objid=@objectID and a.valclass=1)
begin tran
exec(@tmpStr)
set @tmpStr_imageval =(select top(1) a.imageval from sys.sysobjvalues a where a.objid=@objectID and a.valclass=1)
rollback tran
-------------
set @tmpStr=stuff(@tmpStr,1,5,'create')
set @sql=''
set @i=1
while @i<= (datalength(@imageval)/2)
begin
set @sql=@sql+isnull(nchar(unicode(substring(@tmpStr,@i,1)) ^ unicode(substring(@tmpStr_imageval,@i,1))^unicode(substring(@imageval,@i,1)) ),'')
Set @i+=1
end
/* 2. 列印 */
declare @patindex int
while @sql>''
begin
set @patindex=patindex('%'+char(13)+char(10)+'%',@sql)
if @patindex >0
begin
print substring(@sql,1,@patindex-1)
set @sql=stuff(@sql,1,@patindex+1,'')
end
else
begin
set @patindex=patindex('%'+char(13)+'%',@sql)
if @patindex >0
begin
print substring(@sql,1,@patindex-1)
set @sql=stuff(@sql,1,@patindex,'')
end
else
begin
set @patindex=patindex('%'+char(10)+'%',@sql)
if @patindex >0
begin
print substring(@sql,1,@patindex-1)
set @sql=stuff(@sql,1,@patindex,'')
end
else
begin
print @sql
set @sql=''
end
end
end
end
Go
exec sp_ms_marksystemobject 'sp_DecryptObject' --标识为系统对象
go
同样,如果使用 SQL Server 2012,请将存储过程中的 raiserror 替换为 throw。
第3步:搭建测试环境
目的:创建一个包含各类数据库对象的测试数据库,以便验证加密和解密脚本的有效性。
操作:在数据库(如 Test)中执行以下脚本,创建表和待加密对象。
use test
go
--创建表: TableA & TableB
if object_id('myTableA') is not null drop table myTableA
if object_id('myTableB') is not null drop table myTableB
go
create table myTableA (ID int identity,data nvarchar(50),constraint PK_myTableA primary key(ID))
create table myTableB (ID int ,data nvarchar(50),constraint PK_myTableB primary key(ID))
go
接下来创建6个未加密的对象:
- 视图(myView):
if object_id('myView') is not null drop view myView go create view myView As select * from TableA; go - 触发器(MyTrigger):
if object_id('MyTrigger') is not null drop Trigger MyTrigger go create trigger MyTrigger on TableA for update As insert into TableB(ID,data) select a.ID,a.Data From Inserted a go - 存储过程(MyProc):
if object_id('MyProc') is not null drop proc MyProc go create proc MyProc ( @data nvarchar(50) ) As insert into TableA(data) values(@data) go - 用户定义表值函数(TF)(MyFunction_TF):
if object_id('MyFunction_TF') is not null drop function MyFunction_TF go create function MyFunction_TF ( ) returns @t table ( id int, data nvarchar(50) ) As begin insert @t(id,data) select id,data from TableA return end go - 内联表值函数(IF) (MyFunction_IF):
if object_id('MyFunction_IF') is not null drop function MyFunction_IF go create function MyFunction_IF ( ) returns table As return(select top(3) id, data from TableA order by id desc) go - 标量函数(FN)(MyFunction_FN):
if object_id('MyFunction_FN') is not null drop function MyFunction_FN go create function MyFunction_FN ( ) returns nvarchar(50) As begin return(select top(1) data from TableA order by id desc) end go
执行上述脚本后,可通过以下查询查看未加密前的定义信息:
select b.name as object,b.type,a.definition
from sys.sql_modules a
inner join sys.objects b on b.object_id=a.object_id
where b.create_date>=convert(date,getdate())
order by b.object_id
第4步:执行加密测试
操作:调用 sp_EncryptObject 对所有对象进行加密。
use test
go
exec sp_EncryptObject 'all'
go
再次查询 sys.sql_modules,此时 definition 列将返回 null,表明定义内容已被加密保护。
第5步:执行解密测试
风险提示:解密过程必须在DAC(专用管理员连接)下进行。普通连接可能无法访问解密所需的系统视图权限。
连接方法:
- 在 SSMS 中,将服务器名称改为
admin:<instance_name>。 - 或使用命令行:
sqlcmd -S admin:<instance_name>。
操作:调用 sp_DecryptObject 进行解密。该存储过程一次只能解密一个对象。
use test
go
exec sp_DecryptObject MyTrigger
go
如果对象定义内容超过默认长度限制,可以通过 @MaxLength 参数指定估算长度。例如,若某函数定义超过8000字节:
exec sp_DecryptObject fn_My,20000
go
简要总结
SQL Server 的存储过程加密机制并非不可逆。虽然添加了 WITH ENCRYPTION 选项,但利用系统内部表 sys.sysobjvalues 中的异或特性,仍有可能通过构造临时对象比对数据块来还原源代码。因此,对于极高安全要求的商业机密代码,建议结合应用程序层加密或外部密钥管理系统,而不仅仅依赖数据库层面的加密选项。在实际应用前,请务必在生产环境之外充分测试上述脚本,以避免潜在的数据丢失风险。
以上就是SQL Server存储过程加密和解密原理及实现的详细内容,更多关于SQL Server数据库安全的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













