DECRYPTBYKEY (Transact-SQL)

使用对称密钥对数据进行解密。

主题链接图标Transact-SQL 语法约定

语法

DecryptByKey ( { 'ciphertext' | @ciphertext } 
    [ , add_authenticator, { authenticator | @authenticator } ] )

参数

  • ciphertext
    已使用密钥进行加密的数据。ciphertext 的数据类型为 varbinary。

  • @ciphertext
    包含已使用密钥进行加密的数据的 varbinary 类型变量。

  • add_authenticator
    指示是否与明文一起加密验证器。对数据进行加密时,该值必须与传递给 EncryptByKey 的值相同。add_authenticator 的数据类型为 int

  • authenticator
    用于生成验证器的数据。必须与提供给 EncryptByKey 的值相匹配。authenticator 的数据类型为 sysname

  • @authenticator
    包含用于生成验证器的数据的变量。必须与提供给 EncryptByKey 的值相匹配。

返回类型

最大大小为 8,000 个字节的 varbinary。

注释

DecryptByKey 使用对称密钥。该对称密钥必须已经在数据库中打开。可以同时打开多个密钥。不必只在解密密码之前才打开密钥。

对称加密和解密速度相对较快,适于处理大量数据。

权限

需要已在当前会话中打开对称密钥。有关详细信息,请参阅 OPEN SYMMETRIC KEY (Transact-SQL)

示例

使用对称密钥进行解密

以下示例使用对称密钥对密码进行解密。

-- First, open the symmetric key with which to decrypt the data.
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;
GO

-- Now list the original ID, the encrypted ID, and the 
-- decrypted ciphertext. If the decryption worked, the original
-- and the decrypted ID will match.
SELECT NationalIDNumber, EncryptedNationalID 
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalID)) 
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
GO

B. 通过使用对称密钥和验证哈希进行解密

以下示例对使用验证器加密的数据进行解密。

-- First, open the symmetric key with which to decrypt the data
OPEN SYMMETRIC KEY CreditCards_Key11
   DECRYPTION BY CERTIFICATE Sales09;
GO

-- Now list the original card number, the encrypted card number,
-- and the decrypted ciphertext. If the decryption worked, 
-- the original number will match the decrypted number.
SELECT CardNumber, CardNumber_Encrypted 
    AS 'Encrypted card number', CONVERT(nvarchar,
    DecryptByKey(CardNumber_Encrypted, 1 , 
    HashBytes('SHA1', CONVERT(varbinary, CreditCardID)))) 
    AS 'Decrypted card number' FROM Sales.CreditCard;
GO