SQLserver存储过程加密、解密

SQLserver存储过程加密、解密
作者:邱名涛
撰写时间:2019 年 6 月 22 日
关键技术: 数据库存储过程加密、解密

–加密存储过程
–判断表是否存在,如果存在就删除

if object_id(N'dbo.Test',N'U') is not null
drop table dbo.pwdTable
go

–创建表
–Varbinary是一个可以改变长度的二进制数据。
–default(’’)如果某列没有提供具体的值,那么它提供了一个默认值。

create table dbo.Test
	(
	ID int identity(1,1) not null,
	Name nvarchar(max) not null,
	Pord_User varbinary(max) null,
	Pord_Password varbinary(max) null,
	Remarks nvarchar(max) default('')
	)
go

–编辑存储过程
–首先判断存储过程是否存在

if object_id(N'Use_In',N'P') is not null
drop proc Use_In
go
if object_id(N'Usp_de',N'P') is not null
drop proc Usp_de
go
 

–创建加密存储过程

create proc Use_In
@en varchar(20),
@Name nvarchar(max),
@Pord_User nvarchar(max)='',
@Pord_Password nvarchar(max)='',
@Remarks nvarchar(max)=''
as
	begin
		insert Test(Name,Pord_User,Pord_Password,Remarks)
		values
			(
			@Name,
			encryptbypassphrase(@en,cast(@Pord_User as nvarchar(max))),
			encryptbypassphrase(@en,cast(@Pord_Password as nvarchar(max))),
			@Remarks
			)
	end
go

–创建解密存储过程

create proc usp_de
@de varchar(20)--,@pwd_user nvarchar(max) ----取消注释可以按用户名查找
as
	begin
		select
			ID,
			Name,
			cast(decryptbypassphrase(@de,Pord_User) as nvarchar(max)),
			cast(decryptbypassphrase(@de,Pord_Password) as nvarchar(max)),
			Remarks
		from
			Test
		--where					----取消注释可以按用户名查找
		--	pwd_user=encryptbypassphrase(@de,cast(@pwd_user as nvarchar(max)))
	end
go

–允许将显式值插入表的标识列中 ON-允许 OFF-不允许

set identity_insert Test off

–向表内插入加密数据
–I won’t tell you!为加密字符串
–Remarks字段可以不写、

exec Use_In 'I won''t tell you!','乔丹','LiN002','LiN002','管理员'
exec Use_In 'I won''t tell you!','李宁','LiN001','LiN001','客户'
go

–查询表数据

Select * From Test

在这里插入图片描述
–查询表内数据
----如果创建解密存储过程的时候增加了@pwd_user变量,取消注释、填写用户名到’'中,可以按用户名查找

exec usp_de 'I won''t tell you!'--,'' 
go

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Q_MingTao/article/details/93326805