T-SQL DecryptByKey returns 具有列值的 NULL,但不具有列名

T-SQL DecryptByKey returns NULL with Column Value, but not with Column Name

我的数据库中有一个名为 ACCT_FName_encrypt 的加密 varbinary(MAX) 字段。

我可以成功解密此字段:

CONVERT(nvarchar(MAX), DecryptByKey(ACCT_FName_encrypt)) AS 'ACCT_FName_Denc'

但是如果我尝试解密列中的实际值,我会得到 NULL:

CONVERT(nvarchar(MAX), DecryptByKey('0x001D25D87D3D8E49A97863ADC4958E790100000021E26DD2305384AE49EC9329EF2AF8758134F7C946EC9FE024805B8DF21472C4545D461DA9F2B7F96094C2AED09BF4A9')) AS 'ACCT_FName_Denc'

如何在不调用字段的情况下从直接 varbinary 中获取解密值?

尝试将值转换为 Varbinary

select convert(varbinary, '0x001D25D87D3D8E49A97863ADC4958E790100000021E26DD2305384AE49EC9329EF2AF8758134F7C946EC9FE024805B8DF21472C4545D461DA9F2B7F96094C2AED09BF4A9')

它不应该作为字符串传递,之后需要转换为原始类型。完整的工作示例:

OPEN SYMMETRIC KEY Whosebug
DECRYPTION BY PASSWORD = 'pass123_@pass123_@'
GO

DECLARE @ColumnValue NVARCHAR(MAX);
DECLARE @EncrpytionValue VARBINARY(8000);

SET @ColumnValue = REPLICATE (N'A', 12)

SET @EncrpytionValue = ENCRYPTBYKEY( KEY_GUID('Whosebug'), @ColumnValue )

SELECT @EncrpytionValue

SELECT CONVERT(NVARCHAR(MAX), DECRYPTBYKEY(@EncrpytionValue));
SELECT CONVERT(NVARCHAR(MAX), DECRYPTBYKEY(0x00B08017838E6C48889DD12542E4C52002000000A8C910DA1CBFFE30E446358940177F03F912EE36FACF91FA2044BE5C75C9AA69BC15E6425DE52C2A193BA13AEDA90AE2276C244E56692B75CB2D4FDEC8D596F9));

--DROP SYMMETRIC KEY Whosebug;

并且在您的代码中它将只是:

CONVERT(nvarchar(MAX), DecryptByKey(0x001D25D87D3D8E49A97863ADC4958E790100000021E26DD2305384AE49EC9329EF2AF8758134F7C946EC9FE024805B8DF21472C4545D461DA9F2B7F96094C2AED09BF4A9)) AS 'ACCT_FName_Denc'