当前位置:网站首页>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 !
边栏推荐
- The Hal library is configured with a general timer Tim to trigger ADC sampling, and then DMA is moved to the memory space.
- PDF文档签名指南
- Future development blueprint of agriculture and animal husbandry -- vertical agriculture + artificial meat
- Mongodb creates an implicit database as an exercise
- Guide de signature du Code Appx
- Bean 作⽤域和⽣命周期
- IPv4套接字地址结构
- ES6中的函数进阶学习
- China's first electronic audio category "Yamano electronic audio" digital collection is on sale!
- The landing practice of ByteDance kitex in SEMA e-commerce scene
猜你喜欢

Guide de signature du Code Appx

Postman interface test I

The method of word automatically generating directory

【acwing】786. 第k个数

每周推荐短视频:L2级有哪些我们日常中经常会用到的功能?

Garbage disposal method based on the separation of smart city and storage and living digital home mode

电表远程抄表拉合闸操作命令指令

Postman interface test IV

【剑指Offer】42. 栈的压入、弹出序列

This article explains the complex relationship between MCU, arm, muc, DSP, FPGA and embedded system
随机推荐
Parameter sniffing (2/2)
The Hal library is configured with a general timer Tim to trigger ADC sampling, and then DMA is moved to the memory space.
Why are social portals rarely provided in real estate o2o applications?
【acwing】789. 数的范围(二分基础)
CONDA creates virtual environment offline
Word自动生成目录的方法
VS Code指定扩展安装位置
串口通讯继电器-modbus通信上位机调试软件工具项目开发案例
Guid主键
Introduction to uboot
fiddler-AutoResponder
Introduction to energy Router: Architecture and functions for energy Internet
How to cancel automatic saving of changes in sqlyog database
Bit operation ==c language 2
XML配置文件解析与建模
Memory ==c language 1
ORM -- logical relation and & or; Sort operation, update record operation, delete record operation
ORM模型--关联字段,抽象模型类
Postman interface test IV
Wallys/IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL CONCURRENT