本着存储过程举行加密和解密(SQL 2008/SQL 2012)

 

开始:


 在网络直达,看到有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 ';

囤过程不蔓不枝代码:

图片 1图片 2View Code

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的时候,对所有的函数,存储过程,视图和触发器进行加密
    调用方法:
    1. Execute sp_EncryptObject 'All'
    2. 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。

 图片 3

 

 

解密方法:


 解密过程,最重要拔取异或模式:

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


 

图片 4图片 5View Code

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

 图片 6

 

 

搭建测试环境:


每当一个测试环境中(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):

图片 7图片 8View Code

if object_id('myView') is not null drop view myView
go
create view myView
As
select * from TableA;
go

2.触发器(MyTrigger):

图片 9图片 10View Code

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):

图片 11图片 12View Code

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):

图片 13图片 14View Code

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):

图片 15图片 16View Code

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):

图片 17图片 18View Code

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

图片 19

 

加密测试:


 

下边我哪怕透过调用加密存储过程(sp_EncryptObject),五次性对她举行加密:

use test
go
exec sp_EncryptObject 'all'
go

图片 20

当我们重新翻回系统视图sys.sql_modules,会发觉definition列重返的凡null值,表明定义内容就让加密:

图片 21

 

 解密测试:


 

解密过程,必须以DAC连接SQL Server,大家这里例子是由
SSMS(SQL Server Management Studio) 查询编辑器启动 DAC,如图:

图片 22

 

解密存储过程(sp_DecryptObject),只好一浅针对一个囤积过程、函数、视图或触发器,举办解密:

use test
go
exec sp_DecryptObject MyTrigger
go

 图片 23

当定义内容长度超越4000,我们得以指定@马克斯Length的值,如:

exec sp_DecryptObject fn_My,20000
go

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

图片 24

… …

图片 25

 

小结:


 

即便,下面的本子,我曾以SQL Server 2008 R2 和SQL Server
2012测试了,但不能制止有未知错误
。假设你协调当测试点的本子,请不要以生育环境达到。如若你于动过程,遭遇有啊问题仍然暴发什么观点及提议可发email联系自己要跟帖,在是十分感谢!

 

 

 

 

相关文章