[英]Converting Varbinary Data to Nvarchar in sql server
我想加密之前保存密码的密码字段,我的表结构是:
Create table #table (username varchar(50),passwords nvarchar(1000))
Insert into #table values ('abc','pass_123')
现在我正在加密我的密码,如下所示:
update #table set passwords = ENCRYPTBYPASSPHRASE('Key',passwords)
where PATINDEX('%[a0-z9]%',passwords) > 0
但是当我使用以下代码解密密码时:
Select username,convert(varchar(max),DECRYPTBYPASSPHRASE('Key',passwords)) as pwd from #table
它给了我输出
username Passwords
abc p
如果我像这样更改上面的代码:
Select username,convert(nvarchar(max),DECRYPTBYPASSPHRASE('Key',passwords)) as pwd from #table
它给了我正确的输出
username Passwords
abc pass_123
将 varchar 更改为 nvarchar 后适用于已经存在的密码,但是如果有一个新用户并且我在 Insert 期间加密密码,如下所示:
Insert into #table values ('abc',ENCRYPTBYPASSPHRASE('Key','123'))
因此,在使用 nvarchar 解密记录时,我的数据如下所示:
Select username,convert(nvarchar(1000),DECRYPTBYPASSPHRASE('Key',passwords)) as pwd from #table
username pwd
abc pass_123
abc ㈱3
如果我使用 varchar,我的数据将如下所示:
Select username,convert(varchar(max),DECRYPTBYPASSPHRASE('Key',passwords)) as pwd from #table
username pwd
abc p
abc 123
所以基本上,如果我们更新现有记录 nvarchar 用于解密,但如果我们插入新记录 varchar 用于解密。 那么我需要做哪些改变才能通过 varchar 或 nvarchar 获得一致的数据
在您的第一个示例中,您正在从表中的 NVARCHAR 字段读取数据。 即使您插入的字符串是 VARCHAR,SQL Server 也会为您进行转换。
然而,这是两种不同的数据类型(一种是每个字符两个字节,另一个是单字节),因此会变成不同的二进制文件。
函数ENCRYPTBYPASSPHRASE
和DECRYPTBYPASSPHRASE
将任何有效的文本输入作为有效输入。 在您的第一个示例中,您将一个 VARCHAR 字符串插入到表中,并将其转换为 NVARCHAR。 然后将其用作输入(现在是 NVARCHAR)。 但是,如果您直接插入字符串,则将其表示为 VARCHAR,从而以这种格式将其转换为二进制。
使用您当前的表结构:
Insert into #table values ('abc','pass_123')
--Values inserted gets converted to NVARCHAR, even though the string 'pass_123' is VARCHAR
update #table set passwords = ENCRYPTBYPASSPHRASE('Key',passwords)
where PATINDEX('%[a0-z9]%',passwords) > 0
--Thus when calling the update the source string is in NVARCHAR encoding
Select username,convert(nvarchar(max),DECRYPTBYPASSPHRASE('Key',passwords)) as pwd from #table
--So the varbinary is based on the NVARCHAR encoding and thus only viewable when it's made nvarchar
/* This is the same as */
Insert into #table values ('abc',ENCRYPTBYPASSPHRASE('Key',N'123'))
--Value being provided as a parameter to ENCRYPTBYPASSPHRASE is already in NVARCHAR format
Select username,convert(nvarchar(1000),DECRYPTBYPASSPHRASE('Key',passwords)) as pwd from #table
--This ends up with the same result, because the varbinary was based on a NVARCHAR
这纯粹是因为您的源数据类型,在一种情况下您将 NVARCHAR 作为源放入,在另一种情况下放入 VARCHAR。 转换后为 varbinary 提供不同的值。
微软:
从安全的角度来看,这是否是一种正确的方法是一个完全不同的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.