DECRYPTBYASYMKEY()不返回预期值 [英] DECRYPTBYASYMKEY() Not Returning Expected Value

查看:336
本文介绍了DECRYPTBYASYMKEY()不返回预期值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩不对称加密和解密,但是我不明白当我尝试解密值时得到的结果。



为什么这样:

  CREATE ASYMMETRIC KEY myasymkey 
WITH ALGORITHM = RSA_2048
加密PASSWORD ='123pass!';
GO

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

生产 0x47726567 ?我期待它是 Greg



更新:我很笨, 0x47726567 varbinary 转换为 Greg

解决方案

这是正确的 - 当你加密一些被视为一个字节数组的东西,并且被返回。 0x47是G,72是r等。



如果您检查 DecryptByAsmKey ,你会注意到返回类型是varbinary,最大大小为8,000字节。你也会注意到这个例子中的转换。



所以如果你正在加密和解密字符串,你必须像这样转换



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

另请注意,您需要确保转换为varchar(max)或nvarchar(max)取决于您的输入。如果您尝试

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

这将是错误的,因为您的Greg的输入是varchar。


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.

解决方案

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.

这篇关于DECRYPTBYASYMKEY()不返回预期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆