来自DecryptByPassphrase的奇怪结果

时间:2012-03-21 13:40:28

标签: sql-server-2008

我正在尝试加密并解密表中的一列。我的代码是这样的:

drop table EncryptString
go
create table EncryptString(db int, String varchar(100))
go
insert into EncryptString values (2, '123456789')
go
ALTER TABLE EncryptString
ADD StringEncrypted varbinary(256); 
GO

declare @Pass nvarchar(512)
set @Pass = 'somepassword'
update EncryptString set StringEncrypted = ENCRYPTBYPASSPHRASE(@Pass, String, 1,                 convert( varbinary(128), db))
where db = 2

select * From EncryptString

SELECT db, StringEncrypted 
AS 'Encrypted String', CONVERT(nvarchar,
DecryptByPassphrase('somepassword', StringEncrypted, 1 
, CONVERT(varbinary, db)))
AS 'Decrypted String' FROM EncryptString
WHERE db = 2;

为什么我的'Decrypted String'是这样的: ㈱㐳㘵㠷9

由于

1 个答案:

答案 0 :(得分:10)

您正在加密varchar,但在解密时会从二进制nvarchar表示转换为varchar

即。实际上你正在做SELECT CAST(CAST('123456789' AS VARBINARY(30)) AS NVARCHAR(30))

如果将解密位更改为CONVERT(varchar,则按预期工作。如果需要,您可以从varchar投射到nvarchar