KEY_NAME (Transact-SQL)
從對稱金鑰 GUID 或加密文字中傳回對稱金鑰的名稱。
語法
KEY_NAME ( ciphertext | key_guid )
引數
ciphertext
這是對稱金鑰所加密的文字。cyphertext 的類型是 varbinary(8000)。key_guid
這是對稱金鑰的 GUID。key_guid 的類型是 uniqueidentifier。
傳回的類型
varchar(128)
範例
A. 使用 key_guid 來顯示對稱金鑰的名稱
master 資料庫包含名為 ##MS_ServiceMasterKey## 的對稱金鑰。下列範例會從 sys.symmetric_keys 動態管理檢視中取得該金鑰的 GUID,然後將該變數傳遞給 KEY_NAME 函數,以便示範如何傳回對應至 GUID 的名稱。
USE master
GO
DECLARE @guid uniqueidentifier ;
SELECT @guid = key_guid FROM sys.symmetric_keys
WHERE name = '##MS_ServiceMasterKey##' ;
-- Demonstration of passing a GUID to KEY_NAME to receive a name
SELECT KEY_NAME(@guid) AS [Name of Key];
PASSWORD = 'decryption_password'
B. 使用加密文字來顯示對稱金鑰的名稱
下列範例會示範建立對稱金鑰並將資料填入資料表的完整程序。然後,此範例會顯示在傳遞了加密的文字時,KEY_NAME 如何傳回金鑰的名稱。
-- Create a symmetric key
CREATE SYMMETRIC KEY TestSymKey
WITH ALGORITHM = AES_128,
KEY_SOURCE = 'The square of the hypotenuse is equal to the sum of the squares of the sides',
IDENTITY_VALUE = 'Pythagoras'
ENCRYPTION BY PASSWORD = 'pGFD4bb925DGvbd2439587y' ;
GO
-- Create a table for the demonstration
CREATE TABLE DemoKey
(IDCol int IDENTITY PRIMARY KEY,
SecretCol varbinary(256) NOT NULL)
GO
-- Open the symmetric key if not already open
OPEN SYMMETRIC KEY TestSymKey
DECRYPTION BY PASSWORD = 'pGFD4bb925DGvbd2439587y';
GO
-- Insert a row into the DemoKey table
DECLARE @key_GUID uniqueidentifier
SELECT @key_GUID = key_guid FROM sys.symmetric_keys
WHERE name LIKE 'TestSymKey' ;
INSERT INTO DemoKey(SecretCol)
VALUES ( ENCRYPTBYKEY (@key_GUID, 'EncryptedText'))
GO
-- Verify the DemoKey data
SELECT * FROM DemoKey
GO
-- Decrypt the data
DECLARE @ciphertext varbinary(256)
SELECT @ciphertext = SecretCol
FROM DemoKey WHERE IDCol = 1 ;
SELECT CAST (
DECRYPTBYKEY( @ciphertext)
AS varchar(100) ) AS SecretText ;
-- Use KEY_NAME to view the name of the key
SELECT KEY_NAME(@ciphertext) AS [Name of Key] ;