当前位置:网站首页>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 !
边栏推荐
- 串口通讯继电器-modbus通信上位机调试软件工具项目开发案例
- Memory ==c language 1
- MongoDB创建一个隐式数据库用作练习
- 能源路由器入门必读:面向能源互联网的架构和功能
- STM32 ADC和DMA
- Appx code signing Guide
- Writing file types generated by C language
- Video based full link Intelligent Cloud? This article explains in detail what Alibaba cloud video cloud "intelligent media production" is
- 中国首款电音音频类“山野电音”数藏发售来了!
- The new activity of "the arrival of twelve constellations and goddesses" was launched
猜你喜欢

The physical meaning of imaginary number J

web3.0系列之分布式存储IPFS

Pdf document signature Guide

Enterprise practice | construction of banking operation and maintenance index system under complex business relations

Deconvolution popular detailed analysis and nn Convtranspose2d important parameter interpretation

能源路由器入门必读:面向能源互联网的架构和功能

反卷积通俗详细解析与nn.ConvTranspose2d重要参数解释

A wave of open source notebooks is coming

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

Leetcode exercise - 113 Path sum II
随机推荐
Performance optimization record of the company's product "yunzhujia"
虚数j的物理意义
Use of JSON extractor originals in JMeter
PDF文档签名指南
[untitled]
ISP、IAP、ICP、JTAG、SWD的编程特点
Win10 installation vs2015
IPv4套接字地址结构
The method of word automatically generating directory
A wave of open source notebooks is coming
Postman interface test IV
中国首款电音音频类“山野电音”数藏发售来了!
ES类和对象、原型
Horizontal split of database
Google Colab装载Google Drive(Google Colab中使用Google Drive)
Fiddler simulates the interface test
phpcms实现PC网站接入微信Native支付
ORM -- query type, association query
Video based full link Intelligent Cloud? This article explains in detail what Alibaba cloud video cloud "intelligent media production" is
The landing practice of ByteDance kitex in SEMA e-commerce scene