create view v_rand
as
select c=unicode(cast(round(rand()*255,0) as tinyint))
go
create function f_jmstr(@str varchar(8000),@type bit)returns varchar(8000)
/*
*参数说明
*str:要加密的字符串或已经加密后的字符
*type:操作类型--0加密--解密
*返回值说明
*当操作类型为加密时(type--0):返回为加密后的str,即存放于数据库中的字符串
*当操作类型为解密时(type--1):返回为实际字符串,即加密字符串解密后的原来字符串
*/
As
begin
declare @re varchar(8000)--返回值
declare @c int--加密字符
declare @i int
/*
*加密方法为原字符异或一个随机ASCII字符
*/
if @type=0--加密
begin
select @c=c,@re='',@i=len(@str) from v_rand
while @i>0
select @re=nchar(unicode(substring(@str,@i,1))^@c^@i)+@re
,@i=@i-1
set @re=@re+nchar(@c)
end
else--解密
begin
select @i=len(@str)-1,@c=unicode(substring(@str,@i+1,1)),@re=''
while @i>0
select @re=nchar(unicode(substring(@str,@i,1))^@c^@i)+@re ,@i=@i-1
end
return(@re)
end
go
--测试
declare @tempstr varchar(20)
set @tempstr=' 1 2 3aA'
select dbo.f_jmstr(dbo.f_jmstr(@tempstr,0),1)
输出结果
1 2 3aA
如何实现对数据库单个字段进行加密
最新推荐文章于 2025-11-18 20:59:03 发布
博客给出了数据库中字符串加密解密的实现代码。创建了视图 v_rand 用于生成随机 ASCII 字符,定义了函数 f_jmstr 实现加密和解密操作,加密方法是原字符异或随机 ASCII 字符,最后进行了测试,验证了加密解密的正确性。
581

被折叠的 条评论
为什么被折叠?



