DECRYPTBYKEYAUTOCERT (Transact-SQL)

适用于:SQL ServerAzure SQL 托管实例

此函数使用对称密钥解密数据。 该对称密钥使用证书自动解密。

Transact-SQL 语法约定

语法

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

参数

cert_ID

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

cert_password

用于加密证书私钥的密码。 如果数据库主密钥 (DMK) 保护私钥,则可以有一个 NULL 值。 cert_password 具有 nvarchar 数据类型。

'ciphertext'

使用密钥加密的数据字符串。 ciphertext 具有 varbinary 数据类型。

@ciphertext

varbinary 类型的变量,包含使用密钥加密的数据。

add_authenticator

指示原始加密过程是否包含验证器和纯文本以及是否对其进行加密。 必须与在数据加密过程中传递给 ENCRYPTBYKEY 的值匹配。 如果加密过程使用验证器,则 add_authenticator 具有 1 值。 add_authenticator 具有 int 数据类型。

@add_authenticator

变量,指示原始加密过程是否包含验证器和纯文本以及是否对其进行加密。 必须与在数据加密过程中传递给 ENCRYPTBYKEY 的值匹配。 @add_authenticator 具有 int 数据类型。

authenticator

用作验证器生成基础的数据。 必须与提供给 ENCRYPTBYKEY 的值匹配。 authenticator 具有 sysname 数据类型。

@authenticator

包含验证器生成所源自的数据的变量。 必须与提供给 ENCRYPTBYKEY 的值匹配。 @authenticator 具有 sysname 数据类型。

返回类型

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

备注

DECRYPTBYKEYAUTOCERT 合并了 OPEN SYMMETRIC KEY 和 DECRYPTBYKEY 的功能。 在单个操作中,它首先解密对称密钥,然后使用该密钥解密已加密的 ciphertext。

权限

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

示例

此示例演示 DECRYPTBYKEYAUTOCERT 如何简化解密代码。 此代码应在还没有 DMK 的数据库上运行 AdventureWorks2025 。 替换为 <password> 强密码。

--Create the keys and certificate.
USE AdventureWorks2022;

CREATE MASTER KEY ENCRYPTION BY PASSWORD= '<password>';

OPEN MASTER KEY DECRYPTION BY PASSWORD = '<password>';

CREATE CERTIFICATE HumanResources037
    WITH SUBJECT = 'Sammamish HR', EXPIRY_DATE = '10/31/2035';

CREATE SYMMETRIC KEY SSN_Key_01
    WITH ALGORITHM = AES_256
    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;