DECRYPTBYASYMKEY() Not Returning Expected Value

与世无争的帅哥 提交于 2019-12-11 07:54:15

问题


I'm playing around with Asymmetric Encryption and Decryption, but I don't understand the results I'm getting when I try to decrypt values.

Why does this:

CREATE ASYMMETRIC KEY myasymkey 
    WITH ALGORITHM = RSA_2048 
    ENCRYPTION BY PASSWORD = '123pass!'; 
GO

SELECT DECRYPTBYASYMKEY(ASYMKEY_ID('myasymkey'), 
    EncryptByAsymKey(AsymKey_ID('myasymkey'), 'Greg'), 
    N'123pass!');
GO

Produce 0x47726567? I was expecting it to be Greg.

UPDATE: I'm dumb, 0x47726567 is Greg when converted from varbinary.


回答1:


It's right - when you encrypt something it's treated as a byte array and is returned as such. 0x47 is G, 72 is r etc.

If you examine the documentation for DecryptByAsmKey you'll notice the return type is varbinary with a maximum size of 8,000 bytes. You'll also notice the convert in the example.

So if you are encrypting and decrypting strings you must convert like so

SELECT CONVERT(varchar(max),DECRYPTBYASYMKEY(ASYMKEY_ID('myasymkey'), 
    EncryptByAsymKey(AsymKey_ID('myasymkey'), 
    'Greg'), 
    N'123pass!'));

Also note you need to make sure you're converting to varchar(max) or nvarchar(max) depending on your input. If you tried

SELECT CONVERT(nvarchar(max),DECRYPTBYASYMKEY(ASYMKEY_ID('myasymkey'), 
    EncryptByAsymKey(AsymKey_ID('myasymkey'), 
    'Greg'), 
    N'123pass!'));

it would be wrong, as your input of 'Greg' is a varchar.




回答2:


I think 0x47726567 is Greg (in ASCII).




回答3:


All the encryption functions return varbinary values. You will have to cast the result as varchar.



来源:https://stackoverflow.com/questions/8768144/decryptbyasymkey-not-returning-expected-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!