共用方式為


DECRYPTBYKEYAUTOCERT (Transact-SQL)

適用於:SQL ServerAzure SQL 受控執行個體

此函式使用對稱金鑰將資料解密。 該對稱金鑰會使用憑證來自動解密。

Transact-SQL 語法慣例

語法

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

引數

cert_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 KEYDECRYPTBYKEY 的功能。 在單一作業中,它會先將對稱金鑰解密,再使用該金鑰將加密文字解密。

權限

需要對稱金鑰的 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;