Search code examples
sql-serversql-server-2008encryptionencryption-asymmetric

DECRYPTBYASYMKEY() Not Returning Expected Value


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.


Solution

  • 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.