Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange result from DecryptByPassphrase

I am trying encrypt and decrypt one column in table. My code is like this:

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;

Why my 'Decrypted String' is like this: ㈱㐳㘵㠷9

Thanks

like image 454
user1212016 Avatar asked Mar 21 '12 13:03

user1212016


1 Answers

You are encrypting a varchar but then converting to nvarchar from the binary varchar representation when decrypting.

i.e. effectively you are doing SELECT CAST(CAST('123456789' AS VARBINARY(30)) AS NVARCHAR(30))

If you alter the decryption bit to CONVERT(varchar it works as expected. You can then cast from varchar to nvarchar if required.

like image 191
Martin Smith Avatar answered Nov 07 '22 19:11

Martin Smith