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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With