DECRYPTBYKEY (Transact-SQL)
SQL Server 2012
Decrypts data by using a symmetric key.
DecryptByKey uses a symmetric key. This symmetric key must already be open in the database. There can be multiple keys open at the same time. You do not have to open the key immediately before decrypting the cipher text.
Symmetric encryption and decryption is relatively fast, and is suitable for working with large amounts of data.
Requires the symmetric key to have been opened in the current session. For more information, see OPEN SYMMETRIC KEY (Transact-SQL).
A. Decrypting by using a symmetric key
The following example decrypts ciphertext by using a symmetric key.
-- 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. Decrypting by using a symmetric key and an authenticating hash
The following example decrypts data that was encrypted together with an authenticator.
-- 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
