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 的值。

傳回類型

varbinary,大小上限為 8,000 位元組。

備註

DecryptByKey 使用對稱金鑰。這個對稱金鑰必須已在資料庫中開啟。同時可以開啟多個金鑰。為加密文字解密之前,您不需立即開啟金鑰。

對稱加密和解密相當快速,而且很適合處理大量資料。

權限

要求對稱金鑰已經在目前的工作階段中開啟。如需詳細資訊,請參閱<OPEN SYMMETRIC KEY (Transact-SQL)>。

範例

A. 使用對稱金鑰解密

下列範例是利用對稱金鑰為加密文字解密。

-- 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