在網絡上,看到有SQL Server 2000和SQL Server 2005 的存儲過程加密和解密的方法,後來分析了其中的代碼,發現它們的原理都是同樣的。後來本身根據實際的應用環境,編寫了兩個存儲過程,一個加密存儲過程(sp_EncryptObject),和一個解密存儲過程(sp_EncryptObject),它們能夠應用於SQL Server中的儲過程,函數,視圖,以及觸發器。sql
感受這兩個存儲過程蠻有意思的,拿來與你們分享;若是你看過相似的,就看成重溫一下也好。網絡
用於加密的存儲過程 (sp_EncryptObject) :編輯器
存儲過程(sp_EncryptObject)加密的方法是在存儲過程,函數,視圖的「As」位置前加上「with encryption」;若是是觸發器,就在「for」位置前加「with encryption」。ide
若是觸發器是{ AFTER | INSTEAD OF} 須要修改下面代碼"For"位置:函數
if objectproperty(object_id(@Object),'ExecIsAfterTrigger')=0 set @Replace='As' ; else set @Replace='For ';
存儲過程完成代碼:測試
1 Use master 2 Go 3 if object_ID('[sp_EncryptObject]') is not null 4 Drop Procedure [sp_EncryptObject] 5 Go 6 create procedure sp_EncryptObject 7 ( 8 @Object sysname='All' 9 ) 10 as 11 /* 12 當@Object=All的時候,對全部的函數,存儲過程,視圖和觸發器進行加密 13 調用方法: 14 1. Execute sp_EncryptObject 'All' 15 2. Execute sp_EncryptObject 'ObjectName' 16 */ 17 begin 18 set nocount on 19 20 if @Object <>'All' 21 begin 22 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')) 23 begin 24 --SQL Server 2008 25 raiserror 50001 N'無效的加密對象!加密對象必須是函數,存儲過程,視圖或觸發器。' 26 27 --SQL Server 2012 28 --throw 50001, N'無效的加密對象!加密對象必須是函數,存儲過程,視圖或觸發器。',1 29 30 return 31 end 32 33 if exists(select 1 from sys.sql_modules a where a.object_id=object_id(@Object) and a.definition is null) 34 begin 35 --SQL Server 2008 36 raiserror 50001 N'對象已經加密!' 37 38 --SQL Server 2012 39 --throw 50001, N'對象已經加密!',1 40 return 41 end 42 end 43 44 declare @sql nvarchar(max),@C1 nchar(1),@C2 nchar(1),@type nvarchar(50),@Replace nvarchar(50) 45 set @C1=nchar(13) 46 set @C2=nchar(10) 47 48 49 declare cur_Object 50 cursor for 51 select object_name(a.object_id) As ObjectName,a.definition 52 from sys.sql_modules a 53 inner join sys.objects b on b.object_id=a.object_id 54 and b.is_ms_shipped=0 55 and not exists(select 1 56 from sys.extended_properties x 57 where x.major_id=b.object_id 58 and x.minor_id=0 59 and x.class=1 60 and x.name='microsoft_database_tools_support' 61 ) 62 where b.type in('P','V','TR','FN','IF','TF') 63 and (b.name=@Object or @Object='All') 64 and b.name <>'sp_EncryptObject' 65 and a.definition is not null 66 order by Case 67 when b.type ='V' then 1 68 when b.type ='TR' then 2 69 when b.type in('FN','IF','TF') then 3 70 else 4 end,b.create_date,b.object_id 71 72 open cur_Object 73 fetch next from cur_Object into @Object,@sql 74 while @@fetch_status=0 75 begin 76 77 Begin Try 78 79 if objectproperty(object_id(@Object),'ExecIsAfterTrigger')=0 set @Replace='As' ; else set @Replace='For '; 80 81 if (patindex('%'+@C1+@C2+@Replace+@C1+@C2+'%',@sql)>0) 82 begin 83 set @sql=Replace(@sql,@C1+@C2+@Replace+@C1+@C2,@C1+@C2+'With Encryption'+@C1+@C2+@Replace+@C1+@C2) 84 end 85 else if(patindex('%'+@C1+@Replace+@C1+'%',@sql)>0) 86 begin 87 set @sql=Replace(@sql,@C1+@Replace+@C1,@C1+'With Encryption'+@C1+@Replace+@C1) 88 end 89 else if(patindex('%'+@C2+@Replace+@C2+'%',@sql)>0) 90 begin 91 set @sql=Replace(@sql,@C2+@Replace+@C2,@C2+'With Encryption'+@C2+@Replace+@C2) 92 end 93 else if(patindex('%'+@C2+@Replace+@C1+'%',@sql)>0) 94 begin 95 set @sql=Replace(@sql,@C2+@Replace+@C1,@C1+'With Encryption'+@C2+@Replace+@C1) 96 end 97 else if(patindex('%'+@C1+@C2+@Replace+'%',@sql)>0) 98 begin 99 set @sql=Replace(@sql,@C1+@C2+@Replace,@C1+@C2+'With Encryption'+@C1+@C2+@Replace) 100 end 101 else if(patindex('%'+@C1+@Replace+'%',@sql)>0) 102 begin 103 set @sql=Replace(@sql,@C1+@Replace,@C1+'With Encryption'+@C1+@Replace) 104 end 105 else if(patindex('%'+@C2+@Replace+'%',@sql)>0) 106 begin 107 set @sql=Replace(@sql,@C2+@Replace,@C2+'With Encryption'+@C2+@Replace) 108 end 109 110 set @type = 111 case 112 when object_id(@Object,'P')>0 then 'Proc' 113 when object_id(@Object,'V')>0 then 'View' 114 when object_id(@Object,'TR')>0 then 'Trigger' 115 when object_id(@Object,'FN')>0 or object_id(@Object,'IF')>0 or object_id(@Object,'TF')>0 then 'Function' 116 end 117 set @sql=Replace(@sql,'Create '+@type,'Alter '+@type) 118 119 Begin Transaction 120 exec(@sql) 121 print N'已完成加密對象('+@type+'):'+@Object 122 Commit Transaction 123 124 End Try 125 Begin Catch 126 Declare @Error nvarchar(2047) 127 Set @Error='Object: '+@Object+@C1+@C2+'Error: '+Error_message() 128 129 130 Rollback Transaction 131 print @Error 132 print @sql 133 End Catch 134 135 fetch next from cur_Object into @Object,@sql 136 137 end 138 139 close cur_Object 140 deallocate cur_Object 141 end 142 143 Go 144 exec sp_ms_marksystemobject 'sp_EncryptObject' --標識爲系統對象 145 go
若是SQL Server 2012,請修改下面兩個位置的代碼。在SQL Server 2012,建議在使用throw來代替raiserror。fetch
解密方法:ui
解密過程,最重要採用異或方法:加密
[字符1]通過函數 fn_x(x)加密變成[加密後字符1],若是咱們已知[加密後字符1],反過來查[字符1],能夠這樣:spa
[字符1] = [字符2] ^ fn_x([字符2]) ^ [加密後字符1]
這裏我列舉一個簡單的例子:
1 --建立加密函數(fn_x) 2 if object_id('fn_x') is not null drop function fn_x 3 go 4 create function fn_x 5 ( 6 @x nchar(1) 7 )returns nchar(1) 8 as 9 begin 10 return(nchar((65535-unicode(@x)))) 11 end 12 go 13 declare @nchar_1_encrypt nchar(1),@nchar_2 nchar(1) 14 15 16 --對字符'A'進行加密,存入變量@nchar_1_encrypt 17 set @nchar_1_encrypt=dbo.fn_x(N'A') 18 19 20 --參考的字符@nchar_2 21 set @nchar_2='x' 22 23 --算出@nchar_1_encrypt 加密前的字符 24 select nchar(unicode(@nchar_2)^unicode(dbo.fn_x(@nchar_2))^unicode(@nchar_1_encrypt)) as [@nchar_1] 25 26 /* 27 @nchar_1 28 -------------------- 29 A 30 */
[注]: 從SQL Server 2000至 SQL Server 2012 採用異或方法均可以解密
用於解密的存儲過程(sp_DecryptObject):
1 Use master 2 Go 3 if object_ID('[sp_DecryptObject]') is not null 4 Drop Procedure [sp_DecryptObject] 5 Go 6 create procedure sp_DecryptObject 7 ( 8 @Object sysname, --要解密的對象名:函數,存儲過程,視圖或觸發器 9 @MaxLength int=4000 --評估內容的長度 10 ) 11 as 12 set nocount on 13 /* 1. 解密 */ 14 15 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')) 16 begin 17 --SQL Server 2008 18 raiserror 50001 N'無效的對象!要解密的對象必須是函數,存儲過程,視圖或觸發器。' 19 20 --SQL Server 2012 21 --throw 50001, N'無效的對象!要解密的對象必須是函數,存儲過程,視圖或觸發器。',1 22 return 23 end 24 25 if exists(select 1 from sys.sql_modules a where a.object_id=object_id(@Object) and a.definition is not null) 26 begin 27 --SQL Server 2008 28 raiserror 50001 N'對象沒有加密!' 29 30 --SQL Server 2012 31 --throw 50001, N'無效的對象!要解密的對象必須是函數,存儲過程,視圖或觸發器。',1 32 return 33 end 34 35 declare @sql nvarchar(max) --解密出來的SQL語句 36 ,@imageval nvarchar(max) --加密字符串 37 ,@tmpStr nvarchar(max) --臨時SQL語句 38 ,@tmpStr_imageval nvarchar(max) --臨時SQL語句(加密後) 39 ,@type char(2) --對象類型('P','V','TR','FN','IF','TF') 40 ,@objectID int --對象ID 41 ,@i int --While循環使用 42 ,@Oject1 nvarchar(1000) 43 44 set @objectID=object_id(@Object) 45 set @type=(select a.type from sys.objects a where a.object_id=@objectID) 46 47 declare @Space4000 nchar(4000) 48 set @Space4000=replicate('-',4000) 49 50 /* 51 @tmpStr 會構造下面的SQL語句 52 ------------------------------------------------------------------------------- 53 alter trigger Tr_Name on Table_Name with encryption for update as return /**/ 54 alter proc Proc_Name with encryption as select 1 as col /**/ 55 alter view View_Name with encryption as select 1 as col /**/ 56 alter function Fn_Name() returns int with encryption as begin return(0) end/**/ 57 */ 58 set @Oject1=quotename(object_schema_name(@objectID))+'.'+quotename(@Object) 59 set @tmpStr= 60 case 61 when @type ='P ' then N'Alter Procedure '+@Oject1+' with encryption as select 1 as column1 ' 62 when @type ='V ' then N'Alter View '+@Oject1+' with encryption as select 1 as column1 ' 63 when @type ='FN' then N'Alter Function '+@Oject1+'() returns int with encryption as begin return(0) end ' 64 when @type ='IF' then N'Alter Function '+@Oject1+'() returns table with encryption as return(Select a.name from sys.types a) ' 65 when @type ='TF' then N'Alter Function '+@Oject1+'() returns @t table(name nvarchar(50)) with encryption as begin return end ' 66 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 ' 67 end 68 69 70 set @tmpStr=@tmpStr+'/*'+@Space4000 71 set @i=0 72 while @i < (ceiling(@MaxLength*1.0/4000)-1) 73 begin 74 set @tmpStr=@tmpStr+ @Space4000 75 Set @i=@i+1 76 end 77 set @tmpStr=@tmpStr+'*/' 78 79 ------------ 80 set @imageval =(select top(1) a.imageval from sys.sysobjvalues a where a.objid=@objectID and a.valclass=1) 81 82 begin tran 83 exec(@tmpStr) 84 set @tmpStr_imageval =(select top(1) a.imageval from sys.sysobjvalues a where a.objid=@objectID and a.valclass=1) 85 86 rollback tran 87 88 ------------- 89 set @tmpStr=stuff(@tmpStr,1,5,'create') 90 set @sql='' 91 set @i=1 92 while @i<= (datalength(@imageval)/2) 93 begin 94 set @sql=@sql+isnull(nchar(unicode(substring(@tmpStr,@i,1)) ^ unicode(substring(@tmpStr_imageval,@i,1))^unicode(substring(@imageval,@i,1)) ),'') 95 Set @i+=1 96 end 97 98 /* 2. 列印 */ 99 100 101 declare @patindex int 102 while @sql>'' 103 begin 104 105 set @patindex=patindex('%'+char(13)+char(10)+'%',@sql) 106 if @patindex >0 107 begin 108 print substring(@sql,1,@patindex-1) 109 set @sql=stuff(@sql,1,@patindex+1,'') 110 end 111 else 112 begin 113 set @patindex=patindex('%'+char(13)+'%',@sql) 114 if @patindex >0 115 begin 116 print substring(@sql,1,@patindex-1) 117 set @sql=stuff(@sql,1,@patindex,'') 118 end 119 else 120 begin 121 set @patindex=patindex('%'+char(10)+'%',@sql) 122 if @patindex >0 123 begin 124 print substring(@sql,1,@patindex-1) 125 set @sql=stuff(@sql,1,@patindex,'') 126 end 127 else 128 begin 129 print @sql 130 set @sql='' 131 end 132 end 133 end 134 135 end 136 137 Go 138 exec sp_ms_marksystemobject 'sp_DecryptObject' --標識爲系統對象 139 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):
1 if object_id('myView') is not null drop view myView 2 go 3 create view myView 4 As 5 select * from TableA; 6 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):
1 if object_id('MyFunction_TF') is not null drop function MyFunction_TF 2 go 3 create function MyFunction_TF 4 ( 5 ) 6 returns @t table 7 ( 8 id int, 9 data nvarchar(50) 10 ) 11 As 12 begin 13 insert @t(id,data) select id,data from TableA 14 return 15 end 16 go
5.內聯表值函數(IF) (MyFunction_IF):
1 if object_id('MyFunction_IF') is not null drop function MyFunction_IF 2 go 3 create function MyFunction_IF 4 ( 5 ) 6 returns table 7 As 8 return(select top(3) id, data from TableA order by id desc) 9 go
6.標量函數(FN)(MyFunction_FN):
1 if object_id('MyFunction_FN') is not null drop function MyFunction_FN 2 go 3 create function MyFunction_FN 4 ( 5 ) 6 returns nvarchar(50) 7 As 8 begin 9 return(select top(1) data from TableA order by id desc) 10 end 11 go
當執行完了上面的1-6步驟的腳本,咱們經過查詢系統視圖sys.sql_modules,能夠看到未加密前的定義信息:
1 select b.name as object,b.type,a.definition 2 from sys.sql_modules a 3 inner join sys.objects b on b.object_id=a.object_id 4 where b.create_date>=convert(date,getdate()) 5 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測試過,但沒法避免一些未知錯誤 。