SQL Server儲進程加密息爭密道理深刻剖析。本站提示廣大學習愛好者:(SQL Server儲進程加密息爭密道理深刻剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是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 @WordStr='As' ; else set @WordStr='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),@WordStr 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 @WordStr='As' ; else set @WordStr='For ';
if (patindex('%'+@C1+@C2+@WordStr+@C1+@C2+'%',@sql)>0)
begin
set @sql=WordStr(@sql,@C1+@C2+@WordStr+@C1+@C2,@C1+@C2+'With Encryption'+@C1+@C2+@WordStr+@C1+@C2)
end
else if(patindex('%'+@C1+@WordStr+@C1+'%',@sql)>0)
begin
set @sql=WordStr(@sql,@C1+@WordStr+@C1,@C1+'With Encryption'+@C1+@WordStr+@C1)
end
else if(patindex('%'+@C2+@WordStr+@C2+'%',@sql)>0)
begin
set @sql=WordStr(@sql,@C2+@WordStr+@C2,@C2+'With Encryption'+@C2+@WordStr+@C2)
end
else if(patindex('%'+@C2+@WordStr+@C1+'%',@sql)>0)
begin
set @sql=WordStr(@sql,@C2+@WordStr+@C1,@C1+'With Encryption'+@C2+@WordStr+@C1)
end
else if(patindex('%'+@C1+@C2+@WordStr+'%',@sql)>0)
begin
set @sql=WordStr(@sql,@C1+@C2+@WordStr,@C1+@C2+'With Encryption'+@C1+@C2+@WordStr)
end
else if(patindex('%'+@C1+@WordStr+'%',@sql)>0)
begin
set @sql=WordStr(@sql,@C1+@WordStr,@C1+'With Encryption'+@C1+@WordStr)
end
else if(patindex('%'+@C2+@WordStr+'%',@sql)>0)
begin
set @sql=WordStr(@sql,@C2+@WordStr,@C2+'With Encryption'+@C2+@WordStr)
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=WordStr(@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,如圖:
admin:to the instance name in the format sqlcmd -Sadmin:<instance_name>. You can also initiate a DAC from a Query Editor by connecting to admin:<instance_name>.'>
解密存儲進程(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接洽我或跟帖,在此異常感激!