SQL Server储过程加密和解密原理深入分析

开始

——————————————————————————–

在网络上,看到有sql server 2000和sql server 2005 的存储过程加密和解密的方法,后来分析了其中的代码,发现它们的原理都是一样的。后来自己根据实际的应用环境,编写了两个存储过程,一个加密存储过程(sp_encryptobject),和一个解密存储过程(sp_encryptobject),它们可以应用于sql server中的储过程,函数,视图,以及触发器。

感觉这两个存储过程蛮有意思的,拿来与大家分享;如果你看过类似的,就当作重温一下也好。

用于加密的存储过程 (sp_encryptobject) :

——————————————————————————–

存储过程(sp_encryptobject)加密的方法是在存储过程,函数,视图的“as”位置前加上“with encryption”;如果是触发器,就在“for”位置前加“with encryption”。

如果触发器是{ after | instead of} 需要修改下面代码”for”位置:


复制代码 代码如下:

if objectproperty(object_id(@object),’execisaftertrigger’)=0 set @replace=’as’ ; else set @replace=’for ‘;

存储过程完成代码:


复制代码 代码如下:

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

–sql server 2008

raiserror 50001 n’无效的加密对象!加密对象必须是函数,存储过程,视图或触发器。’

–sql server 2012

–throw 50001, n’无效的加密对象!加密对象必须是函数,存储过程,视图或触发器。’,1

return

end

if exists(select 1 from sys.sql_modules a where a.object_id=object_id(@object) and a.definition is null)

begin

–sql server 2008

raiserror 50001 n’对象已经加密!’

–sql server 2012

–throw 50001, n’对象已经加密!’,1

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 ‘;

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

else if(patindex(‘%’+@c2+@replace+@c2+’%’,@sql)>0)

begin

set @sql=replace(@sql,@c2+@replace+@c2,@c2+’with encryption’+@c2+@replace+@c2)

end

else if(patindex(‘%’+@c2+@replace+@c1+’%’,@sql)>0)

begin

set @sql=replace(@sql,@c2+@replace+@c1,@c1+’with encryption’+@c2+@replace+@c1)

end

else if(patindex(‘%’+@c1+@c2+@replace+’%’,@sql)>0)

begin

set @sql=replace(@sql,@c1+@c2+@replace,@c1+@c2+’with encryption’+@c1+@c2+@replace)

end

else if(patindex(‘%’+@c1+@replace+’%’,@sql)>0)

begin

set @sql=replace(@sql,@c1+@replace,@c1+’with encryption’+@c1+@replace)

end

else if(patindex(‘%’+@c2+@replace+’%’,@sql)>0)

begin

set @sql=replace(@sql,@c2+@replace,@c2+’with encryption’+@c2+@replace)

end

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

deallocate cur_object

end

go

exec sp_ms_marksystemobject ‘sp_encryptobject’ –标识为系统对象

go

如果sql server 2012,请修改下面两个位置的代码。在sql server 2012,建议在使用throw来代替raiserror。

 


解密方法

解密过程,最重要采用异或方法:

[字符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)

)returns 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 采用异或方法都可以解密

用于解密的存储过程(sp_decryptobject):


复制代码 代码如下:

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

–sql server 2008

raiserror 50001 n’无效的对象!要解密的对象必须是函数,存储过程,视图或触发器。’

–sql server 2012

–throw 50001, n’无效的对象!要解密的对象必须是函数,存储过程,视图或触发器。’,1

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

–sql server 2008

raiserror 50001 n’对象没有加密!’

–sql server 2012

–throw 50001, n’无效的对象!要解密的对象必须是函数,存储过程,视图或触发器。’,1

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,请修改下面两个位置的代码。方法类似于前面的加密过程:

搭建测试环境

——————————————————————————–

在一个测试环境中(db: test),先执行上面的加密存储过程(sp_encryptobject)和解密存储过程(sp_encryptobject);再创建两个表:tablea & tableb


复制代码 代码如下:

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个未加密的对象(对象类型包含 ‘p’,’v’,’tr’,’fn’,’if’,’tf’):

1.视图(myview):


复制代码 代码如下:

if object_id(‘myview’) is not null drop view myview

go

create view myview

as

select * from tablea;

go

2.触发器(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

3.存储过程(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

4.用户定义表值函数(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

5.内联表值函数(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

6.标量函数(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

当执行完了上面的1-6步骤的脚本,我们通过查询系统视图sys.sql_modules,可以看到未加密前的定义信息:


复制代码 代码如下:

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

 


加密测试

——————————————————————————–

下面我就通过调用加密存储过程(sp_encryptobject),一次性对它们进行加密:


复制代码 代码如下:

use test

go

exec sp_encryptobject ‘all’

go

 

当我们再查回系统视图sys.sql_modules,会发现definition列返回的是null值,说明定义内容已经给加密:


解密测试

——————————————————————————–

解密过程,必须在dac连接sql server,我们这里例子是从 ssms(sql server management studio) 查询编辑器启动 dac,如图:


 

解密存储过程(sp_decryptobject),只能一次对一个存储过程、函数、视图或触发器,进行解密:


复制代码 代码如下:

use test

go

exec sp_decryptobject mytrigger

go

 

当定义内容长度超过4000,我们可以指定@maxlength的值,如:


复制代码 代码如下:

exec sp_decryptobject fn_my,20000

go

这里(fn_my)是一个函数,定义内容超过了8000: 

… …

 


小结

——————————————————————————–

虽然,上面的脚本,我已经在sql server 2008 r2 和sql server 2012测试过,但无法避免一些未知错误 。如果你自己在测试上面的脚本,请不要在生产环境上。如果你在应用过程,碰到有什么问题或有什么意见和建议可以发email联系我或跟帖,在此非常感谢!

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐