当前位置:网站首页>Encrypt and decrypt stored procedures (SQL 2008/sql 2012)
Encrypt and decrypt stored procedures (SQL 2008/sql 2012)
2022-07-07 10:15:00 【Guoguo】
Start :
On the network , See there are SQL Server 2000 and SQL Server 2005 Methods of encrypting and decrypting stored procedures , Later, I analyzed the code , It is found that their principle is the same . Later, according to the actual application environment , Write two stored procedures , An encrypted stored procedure (sp_EncryptObject), And a decryption stored procedure (sp_EncryptObject), They can be applied to SQL Server Storage process in , function , View , And triggers .
I think these two stored procedures are quite interesting , To share with you ; If you have seen similar , Just review it .
Stored procedures for encryption (sp_EncryptObject) :
stored procedure (sp_EncryptObject) The encryption method is in the stored procedure , function , View's “As” Add before position “with encryption”; If it is a trigger , It's just “for” Add... Before the position “with encryption”.
If the trigger is { AFTER | INSTEAD OF} The following code needs to be modified "For" Location :
if objectproperty(object_id(@Object),'ExecIsAfterTrigger')=0 set @Replace='As' ; else set @Replace='For ';
Stored procedure completion code :
View Code
If SQL Server 2012, Please modify the code in the following two positions . stay SQL Server 2012, It is recommended to use throw Instead of raiserror.
Decryption method :
The decryption process , The most important method is XOR :
[ character 1] Through functions fn_x(x) Encryption becomes [ Encrypted characters 1], If we know [ Encrypted characters 1], Reverse check [ character 1], It can be like this :
[ character 1] = [ character 2] ^ fn_x([ character 2]) ^ [ Encrypted characters 1]
Here I give a simple example :
-- Create encryption function (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) -- The character 'A' To encrypt , Storing variables @nchar_1_encrypt set @nchar_1_encrypt=dbo.fn_x(N'A') -- Referenced characters @nchar_2 set @nchar_2='x' -- Work out @nchar_1_encrypt Characters before encryption select nchar(unicode(@nchar_2)^unicode(dbo.fn_x(@nchar_2))^unicode(@nchar_1_encrypt)) as [@nchar_1] /* @nchar_1 -------------------- A */
[ notes ]: from SQL Server 2000 to SQL Server 2012 Using XOR method can decrypt
Stored procedure for decryption (sp_DecryptObject):
Use master Go if object_ID('[sp_DecryptObject]') is not null Drop Procedure [sp_DecryptObject] Go create procedure sp_DecryptObject ( @Object sysname, -- The name of the object to decrypt : function , stored procedure , View or trigger @MaxLength int=4000 -- Length of evaluation content ) as set nocount on /* 1. Decrypt */ 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' Invalid object ! The object to decrypt must be a function , stored procedure , View or trigger .' --SQL Server 2012 --throw 50001, N' Invalid object ! The object to decrypt must be a function , stored procedure , View or trigger .',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' Object is not encrypted !' --SQL Server 2012 --throw 50001, N' Invalid object ! The object to decrypt must be a function , stored procedure , View or trigger .',1 return end declare @sql nvarchar(max) -- Decrypted SQL sentence ,@imageval nvarchar(max) -- Encrypted string ,@tmpStr nvarchar(max) -- temporary SQL sentence ,@tmpStr_imageval nvarchar(max) -- temporary SQL sentence ( After encryption ) ,@type char(2) -- object type ('P','V','TR','FN','IF','TF') ,@objectID int -- object ID ,@i int --While Recycling ,@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 Will construct the following SQL sentence ------------------------------------------------------------------------------- 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. Print */ 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' -- Identify as system object go
If SQL Server 2012, Please modify the code in the following two positions . The method is similar to the previous encryption process :
Set up the test environment :
In a test environment (DB: Test), First execute the above encrypted stored procedure (sp_EncryptObject) And decrypt stored procedures (sp_EncryptObject); Create two more tables :TableA & TableB
use test go -- Create table : 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
Next , We want to create 6 Unencrypted objects ( The object type contains 'P','V','TR','FN','IF','TF'):
1. View (myView):
View Code
2. trigger (MyTrigger):
View Code
3. stored procedure (MyProc):
View Code
4. User defined table valued functions (TF)(MyFunction_TF):
View Code
5. Inline table valued functions (IF) (MyFunction_IF):
View Code
6. Scalar function (FN)(MyFunction_FN):
View Code
When the above 1-6 Script for step , We query the system view sys.sql_modules, You can see the definition information before encryption :
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
Encryption test :
Next, I will call the encrypted stored procedure (sp_EncryptObject), Encrypt them at one time :
use test go exec sp_EncryptObject 'all' go
When we check back the system view sys.sql_modules, Will find definition Column returns null value , Note that the definition content has been encrypted :
Decryption test :
The decryption process , Must be in DAC Connect SQL Server, Our example here is from SSMS(SQL Server Management Studio) The query editor starts DAC, Pictured :
Decrypt stored procedures (sp_DecryptObject), Only one stored procedure at a time 、 function 、 View or trigger , To decrypt :
use test go exec sp_DecryptObject MyTrigger go
When the definition content length exceeds 4000, We can specify @MaxLength Value , Such as :
exec sp_DecryptObject fn_My,20000 go
here (fn_My) It's a function , The definition content exceeds 8000:
... ...
Summary :
although , The script above , I am already in SQL Server 2008 R2 and SQL Server 2012 tested , But some unknown mistakes cannot be avoided . If you are testing the above script yourself , Please do not in the production environment . If you are in the application process , If you have any problems or comments and suggestions, you can send email Contact me or post , Thank you very much !
边栏推荐
猜你喜欢
【剑指Offer】42. 栈的压入、弹出序列
Video based full link Intelligent Cloud? This article explains in detail what Alibaba cloud video cloud "intelligent media production" is
Postman interface test VI
ORM模型--数据记录的创建操作,查询操作
ORM model -- creation and query of data records
Web3.0 series distributed storage IPFs
Win10 installation vs2015
arcgis操作:dwg数据转为shp数据
Internship log - day04
Delete a record in the table in pl/sql by mistake, and the recovery method
随机推荐
【学习笔记-李宏毅】GAN(生成对抗网络)全系列(一)
How to cancel automatic saving of changes in sqlyog database
Can I open a stock trading account online? Is it safe
【剑指Offer】42. 栈的压入、弹出序列
C#记录日志方法
【acwing】786. 第k个数
Weekly recommended short videos: what are the functions of L2 that we often use in daily life?
ORM -- logical relation and & or; Sort operation, update record operation, delete record operation
Video based full link Intelligent Cloud? This article explains in detail what Alibaba cloud video cloud "intelligent media production" is
ES6中的函数进阶学习
嵌入式背景知识-芯片
Performance optimization record of the company's product "yunzhujia"
UnityWebRequest基础使用之下载文本、图片、AB包
LeetCode 练习——113. 路径总和 II
ORM -- database addition, deletion, modification and query operation logic
.NET配置系统
Garbage disposal method based on the separation of smart city and storage and living digital home mode
运用tensorflow中的keras搭建卷积神经网络
Postman interface test VI
In addition to the objective reasons for overtime, what else is worth thinking about?