KEY_NAME (Transact-SQL)
从对称密钥 GUID 或密码文本返回对称密钥的名称。
语法
KEY_NAME ( ciphertext | key_guid )
参数
ciphertext
是对称密钥加密的文本。varbinary(8000) 的数据类型为 cyphertext。key_guid
是对称密钥的 GUID。uniqueidentifier 的数据类型为 key_guid。
返回类型
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];
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] ;