当前位置:网站首页>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 landing practice of ByteDance kitex in SEMA e-commerce scene
- Postman interface test VII
- 高数_第1章空间解析几何与向量代数_向量的数量积
- The request object parses the request body and request header parameters
- Performance optimization record of the company's product "yunzhujia"
- Programming features of ISP, IAP, ICP, JTAG and SWD
- Fiddler break point
- Interface test
- This article explains the complex relationship between MCU, arm, muc, DSP, FPGA and embedded system
猜你喜欢
Official media attention! The list of top 100 domestic digital collection platforms was released, and the industry accelerated the healthy development of compliance
Some thoughts on the testing work in the process of R & D
【acwing】786. 第k个数
ORM -- grouping query, aggregation query, query set queryset object properties
Garbage disposal method based on the separation of smart city and storage and living digital home mode
ArcGIS operation: batch modify attribute table
官媒关注!国内数字藏品平台百强榜发布,行业加速合规健康发展
Wallys/IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL CONCURRENT
Agile course training
【学习笔记-李宏毅】GAN(生成对抗网络)全系列(一)
随机推荐
Wallys/IPQ6010 (IPQ6018 FAMILY) EMBEDDED BOARD WITH ON-BOARD WIFI DUAL BAND DUAL CONCURRENT
Postman tutorial - scripting
web3.0系列之分布式存储IPFS
电表远程抄表拉合闸操作命令指令
Advanced function learning in ES6
Finally, there is no need to change a line of code! Shardingsphere native driver comes out
The Hal library is configured with a general timer Tim to trigger ADC sampling, and then DMA is moved to the memory space.
串口通讯继电器-modbus通信上位机调试软件工具项目开发案例
request对象对请求体,请求头参数的解析
Interface test
The landing practice of ByteDance kitex in SEMA e-commerce scene
There is a problem using Chinese characters in SQL. Who has encountered it? Such as value & lt; & gt;` None`
Word自动生成目录的方法
【剑指Offer】42. 栈的压入、弹出序列
一文讲解单片机、ARM、MUC、DSP、FPGA、嵌入式错综复杂的关系
C logging method
为什么安装mysql时starting service报错?(操作系统-windows)
虚数j的物理意义
能源路由器入门必读:面向能源互联网的架构和功能
Postman interface test II