Let's say we have some data that is encrypted and we would like to find out what key was used to perform the encryption. SQL Server 2005 knows what key was used to encrypt the data because the key identifier (the key_guid value) is prefixed to the encrypted data. We can find out the key same as SQL Server does with a one-line TSQL statement. Here's a small demo that wraps that one-line statement in a function for easier use:
-- Set up a database for this demo--
use
-- We use the identity_value clause to obtain the same fixed GUID on all systems--
-- The following query should return-- 5D910600-5D5F-874F-54F5-1892D884C477--
-- create a simple function to return the guid of the key that was used to encrypt a piece of data--
-- encrypt using skey and use the key_guid_from_bytes function to examine the encrypted data-- we should retrieve the key guid - 5D910600-5D5F-874F-54F5-1892D884C477 and the key name - skey--
select
close
-- Cleanup--