DECRYPTBYKEYAUTOCERT (Transact-SQL)

使用通过证书自动解密的对称密钥进行解密。

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

语法

DecryptByKeyAutoCert ( cert_ID , cert_password 
        , { 'ciphertext' | @ciphertext }
    [ , { add_authenticator | @add_authenticator } 
    [ , { authenticator | @authenticator } ] ] )

参数

  • cert_ID
    用于保护对称密钥的证书的 ID。cert_ID 的数据类型为 int。

  • cert_password
    用于保护证书私钥的密码。如果私钥受数据库主密钥保护,则该值可以是 NULL。cert_password 的数据类型为 varchar。

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

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

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

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

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

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

返回类型

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

注释

DecryptByKeyAutoCert 组合了 OPEN SYMMETRIC KEY 和 DecryptByKey 的功能。在单个操作中,它可以解密对称密钥,并使用该密钥解密密码文本。

权限

需要对对称密钥拥有 VIEW DEFINITION 权限以及对证书拥有 CONTROL 权限。

示例

下例显示如何用 DecryptByKeyAutoCert 来简化执行解密的代码。应在还没有数据库主密钥的 AdventureWorks2008R2 数据库上运行此代码。

--Create the keys and certificate.
USE AdventureWorks2008R2;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'mzkvdlk979438teag$$ds987yghn)(*&4fdg^';
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'mzkvdlk979438teag$$ds987yghn)(*&4fdg^';
CREATE CERTIFICATE HumanResources037 
   WITH SUBJECT = 'Sammamish HR', 
   EXPIRY_DATE = '10/31/2009';
CREATE SYMMETRIC KEY SSN_Key_01 WITH ALGORITHM = DES
    ENCRYPTION BY CERTIFICATE HumanResources037;
GO
----Add a column of encrypted data.
ALTER TABLE HumanResources.Employee
    ADD EncryptedNationalIDNumber varbinary(128); 
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037 ;
UPDATE HumanResources.Employee
SET EncryptedNationalIDNumber
    = EncryptByKey(Key_GUID('SSN_Key_01'), NationalIDNumber);
GO
--
--Close the key used to encrypt the data.
CLOSE SYMMETRIC KEY SSN_Key_01;
--
--There are two ways to decrypt the stored data.
--
--OPTION ONE, using DecryptByKey()
--1. Open the symmetric key
--2. Decrypt the data
--3. Close the symmetric key
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;
SELECT NationalIDNumber, EncryptedNationalIDNumber  
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalIDNumber)) 
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
CLOSE SYMMETRIC KEY SSN_Key_01;
--
--OPTION TWO, using DecryptByKeyAutoCert()
SELECT NationalIDNumber, EncryptedNationalIDNumber 
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKeyAutoCert ( cert_ID('HumanResources037') , NULL ,EncryptedNationalIDNumber)) 
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;