1. 程式人生 > >SQL 2008 r2 儲存過程 加密解密

SQL 2008 r2 儲存過程 加密解密

用於加密的儲存過程 (sp_EncryptObject) :

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 (

[email protected] 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('%'[email protected][email protected][email protected][email protected][email protected]+'%',@sql)>0)
            begin
                set @sql=Replace(@sql,@[email protected][email protected][email protected][email protected],@[email protected]+'With Encryption'[email protected][email protected][email protected][email protected][email protected])
            end
            else if(patindex('%'[email protected][email protected][email protected]+'%',@sql)>0)
            begin
                set @sql=Replace(@sql,@[email protected][email protected],@C1+'With Encryption'[email protected][email protected][email protected])
            end
            else if(patindex('%'[email protected][email protected][email protected]+'%',@sql)>0)
            begin
                set @sql=Replace(@sql,@[email protected][email protected],@C2+'With Encryption'[email protected][email protected][email protected])
            end
            else if(patindex('%'[email protected][email protected][email protected]+'%',@sql)>0)
            begin
                set @sql=Replace(@sql,@[email protected][email protected],@C1+'With Encryption'[email protected][email protected][email protected])
            end
            else if(patindex('%'[email protected][email protected][email protected]+'%',@sql)>0)
            begin
                set @sql=Replace(@sql,@[email protected][email protected],@[email protected]+'With Encryption'[email protected][email protected][email protected])
            end
            else if(patindex('%'[email protected][email protected]+'%',@sql)>0)
            begin
                set @sql=Replace(@sql,@[email protected],@C1+'With Encryption'[email protected][email protected])
            end
            else if(patindex('%'[email protected][email protected]+'%',@sql)>0)
            begin
                set @sql=Replace(@sql,@[email protected],@C2+'With Encryption'[email protected][email protected])
            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 '[email protected],'Alter '[email protected])
           
            Begin Transaction
            exec(@sql)           
            print N'已完成加密物件('[email protected]+'):'[email protected]           
            Commit Transaction
           
        End Try
        Begin Catch
            Declare @Error nvarchar(2047)
            Set @Error='Object: '[email protected][email protected][email protected]+'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

用於解密的儲存過程(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 [email protected])
 
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 '[email protected]+' with encryption as select 1 as column1 '
            when @type ='V ' then N'Alter View '[email protected]+' with encryption as select 1 as column1 '
            when @type ='FN' then N'Alter Function '[email protected]+'() returns int with encryption as begin return(0) end '
            when @type ='IF' then N'Alter Function '[email protected]+'() returns table with encryption as return(Select a.name from sys.types a) '
            when @type ='TF' then N'Alter Function '[email protected]+'() returns @t table(name nvarchar(50)) with encryption as begin return end '
            else 'Alter Trigger '[email protected]+'on '+quotename(object_schema_name(@objectID))+'.'+(select Top(1) quotename(object_name(parent_id)) from sys.triggers a where [email protected])+' with encryption for update as return '
        end       
 
   
set @[email protected]+'/*'[email protected]
set @i=0
while @i < (ceiling(@MaxLength*1.0/4000)-1)
begin
    set @[email protected]+ @Space4000
    Set @[email protected]+1
end
set @[email protected]+'*/'
 
------------
set @imageval =(select top(1) a.imageval from sys.sysobjvalues a where [email protected] and a.valclass=1)
 
begin tran
exec(@tmpStr)
set @tmpStr_imageval =(select top(1) a.imageval from sys.sysobjvalues a where [email protected] 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 @[email protected]+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

解密測試:

解密過程,必須在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 2008 r2 儲存過程 加密解密

用於加密的儲存過程 (sp_EncryptObject) : Use master Go if object_ID('[sp_EncryptObject]') is not null     Drop Procedure [sp_EncryptObject] Go crea

MSSQL 2008、2012儲存過程加密解密

1. 必須在DAC連線SQL Server 不然會報錯: 訊息 208,級別 16,狀態 1,過程 sp_DecryptObject,第 75 行 物件名 'sys.sysobjvalues' 無效。 2. 建立加(解)密過程儲存過程 3. 執行儲存過程   用於加

(收藏)SQL SERVER 儲存過程加密解密

create PROCEDURE sp_decrypt(@objectname varchar(50))ASbeginset nocount on--CSDN:j9988 copyright:2004.07.15 --V3.2 --破解位元組不受限制,適用於SQLSERVER

SQL Server 2008 r2 安裝過程圖解

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

Sql Server 2008儲存過程傳入表值引數

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

SQL SERVER儲存過程加密和安全上下文

對SQL Server 2008的安全入門略作小結,以作備忘。本文涉及兩個應用:儲存過程加密和安全上下文。 <一>儲存過程加密 SQL server,我已經成了儲存過程的忠實擁躉。在直接使用SQL語句還是儲存過程來處理業務邏輯時,我基本會毫不猶豫地選擇後者。 理由如下:

無意中發現的sql server 儲存過程加密破解方法

轉自:https://blog.csdn.net/gatr/article/details/51226122  儲存過程是資料庫中一個非常重要的該部分,很多業務邏輯都可能寫在儲存過程裡面,為了安全,部分儲存過程是加密存放的,如果我們想看到原始碼,就非常困難了,在sql  se

SQL Server 2008(R2)安裝過程視窗關閉或者出現could not open key

1、開啟登錄檔(win+R,輸入regedit,回車) 2、開啟目錄HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components

C#呼叫Sql Server 2008儲存過程流程

前言 最近用到了sql server 2008的儲存過程,特此整理成文 流程步驟 1.獲取連結 SqlConnection myConnection = new SqlConnec

sql server 2000/2005/2008 判斷儲存過程、觸發器、檢視是否存在並刪除

--判斷是否存在addOneArticle這個儲存過程 if Exists(select name from sysobjects where NAME = 'addOneArticle' and type='P')     drop procedure addOneArticle --判斷是否存在coun

SQL Server 與儲存過程相關的資源網址

儲存過程相關文章 引用連線: 1、SQL server儲存過程建立與使用----http://blog.csdn.net/miniduhua/article/details/52102176 2、SQLSERVER儲存過程基本語法----http://www.cnb

sql在所有儲存過程中查詢包含某字串的執行語句

直接在查詢分析器中執行以下程式碼就行: 方法一) select name from sysobjects o, syscomments s where o.id = s.id and text like '%test%' and o.xtype = 'P'   方法二)

T-SQL 有引數儲存過程的建立與執行

1 use StudentManager 2 go 3 if exists(select * from sysobjects where name='usp_ScoreQuery2') 4 drop procedure usp_ScoreQuery2 5 go 6 --建立帶引數的儲存過程

T-SQL 帶引數儲存過程

建立帶引數的儲存過程 1 use StudentManager 2 go 3 if exists(select * from sysobjects where name='usp_ScoreQuery4') 4 drop procedure usp_ScoreQuery4 5 go 6 c

asp執行sql語句、儲存過程的幾種方法

使用connection物件 會返回一個關閉的recordset記錄集,此記錄集不要再次宣告關閉 建議在update、insert、delete時使用 strCon="provider=sqloledb;data source=servername;initial catalog

資料庫——SQL Server的儲存過程

上一篇部落格總結了許多資料庫常用的SQL語句,今天我們就來看一下SQL的儲存過程。 簡單來說,儲存過程就是一條或者多條sql語句的集合,可視為批處理檔案,但是其作用不僅限於批處理。 本篇主要介紹變數的使用,儲存過程和儲存函式的建立,呼叫,檢視,修改以及刪除操作。上一篇部落格對這一部分內容也有

LINQ to SQL語句之儲存過程

源地址連線: LINQ to SQL語句之儲存過程 在我們編寫程式中,往往需要一些儲存過程,在LINQ to SQL中怎麼使用呢?也許比原來的更簡單些。下面我們以NORTHWND.MDF資料庫中自帶的幾個儲存過程來理解一下。 1.標量返回 在資料庫中,有名為Customers Co

MY-SQL-----資料庫---索引---儲存過程(後)

   索引 索引是一種特殊的檔案,它們包含著對資料表裡所有記錄的引用指標。 它是對資料庫表中一列或多列的值進行排序的一種結構。 簡單理解 資料庫索引好比是一本書前面的目錄,能夠加快資料庫的查詢速度, 資料庫索引就是為了提高表的搜尋效率而對某些欄位中的值建立的目錄。 建立

Sql Server在儲存過程裡面使用遊標遍歷一個表

這裡關於SqlServer有兩個知識點:一個是使用遊標遍歷表,另一個是使用if not exists的sql語句進行插入。 一、使用遊標遍歷表   這個表可以是資料庫的表,也可以是外面DataTable型別的引數傳進去,使用遊標可以概括為以下步驟:宣告遊標、開啟遊標、讀取

Java呼叫SQL Server的儲存過程詳解

                本文較長,包含了如下幾部分                    1使用不帶引數的儲存過程     使用 JDBC 驅動程式呼叫不帶引數的儲存過程時,必須使用 call SQL 轉義序列。不帶引數的 call 轉義序列的語法如下所示: {call procedure-name}