开发者

Retrieving rows saved with encryptbypassphrase

开发者 https://www.devze.com 2023-04-04 12:45 出处:网络
I am new to encryption. I need to keep a field encrypted in a table (DocNumber). I keep this as an encrypted varbinary field by setting:

I am new to encryption. I need to keep a field encrypted in a table (DocNumber). I keep this as an encrypted varbinary field by setting:

   docNumber = ENCRYPTBYPASSPHRASE('password', @docnumber)

When I want to query the table using docnumber I do the following:

   WHERE docNumber = DECRYPTBYPASSPHRASE('password', @docNumber)

However it fails to return eligible records. Then I observed that if I call ENCRYPTBYPASSPHRASE() repeatedly with same password 开发者_如何学Goand value, I end up getting different encrypted values. Where am I making the mistake? How do you normally tackle this?


I've always used it this way, just a slightly different way to organize the predicate:

WHERE CONVERT(VARCHAR(64), DECRYPTBYPASSPHRASE('password', docNumber)) = @docNumber;

The difference is that you are running the decrypt on the original value, which includes the cipher at save time, whereas in the version you were trying, you are decrypting again and this generates a different cipher.

EDIT adding a sample using HASHBYTES():

USE tempdb;
GO
CREATE TABLE dbo.enctest(x VARBINARY(64));
GO
INSERT dbo.enctest(x) SELECT HASHBYTES('SHA1', 'foo');
INSERT dbo.enctest(x) SELECT HASHBYTES('SHA1', 'bar');
GO
SELECT x FROM dbo.enctest WHERE x = HASHBYTES('SHA1', 'foo');
GO
DROP TABLE dbo.enctest;
GO
0

精彩评论

暂无评论...
验证码 换一张
取 消