可用于利用DecryptByKeyAutoCert
函数自动解密数据而无需显式打开密钥的视图。(需要对对称密钥的 VIEW DEFINITION 权限和对证书的 CONTROL 权限。)
--Create the keys and certificate.
USE AdventureWorks2012;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'mzkvdlk979438teag$$ds987yghn)(*&4fdg^';
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'mzkvdlk979438teag$$ds987yghn)(*&4fdg^';
CREATE CERTIFICATE HumanResources037
WITH SUBJECT = 'Sammamish HR',
EXPIRY_DATE = '10/31/2009';
CREATE SYMMETRIC KEY SSN_Key_01 WITH ALGORITHM = DES
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;
考虑到CLOSE SYMMETRIC KEY的评论(突出显示我的)
安全最佳实践通常建议让安全机制(对称密钥)在必要的最短时间内打开,并且仅在必要的范围(存储过程)内打开。
参考DECRYPTBYKEYAUTOCERT中的示例代码,基本上有两种方法可以解密列加密数据。
选项一
DecryptByKey
,然后在返回控制之前关闭密钥。选项二
DecryptByKeyAutoCert
函数自动解密数据而无需显式打开密钥的视图。(需要对对称密钥的 VIEW DEFINITION 权限和对证书的 CONTROL 权限。)