Using the MVC-Mini-Profiler with Entity Framework
[
SET @Result = EncryptByKey(Key_GUID('MySymmetricKeyName'), @ValueToEncrypt)
Note that the result of the above encryption is of type varbinary(256), and if you would like to store the value in a column to use this type.
Decrypting Data
You can decrypt data by using the DecryptByKey function, like so:
DECLARE @Result varchar(max)
SET @Result = DecryptByKey(@ValueToDecrypt)
Make sure you decrypt to the same type that you encrypted in the first place. In my example I encrypted a varchar(max), so I also decrypted to a varchar(max).
Because symmetric keys use time based sessions, you cannot open them inside a function, however you can get around this by opening them first with a Stored Procedure, and then calling the function. Here’s an Example of the setup I have going.
The OpenKeys Stored Procedure
CREATE PROCEDURE OpenKeys
AS
BEGIN
SET NOCCOUNT ON;
BEGIN TRY
OPEN SYMMETRIC KEY MySymmetricKeyName
DECRYPTION BY CERTIFICATE MyCertificateName
END TRY
BEGIN CATCH
-- Handle non-existant key here
END CATCH
END
The Encrypt Function
CREATE FUNCTION Encrypt
(
@ValueToEncrypt varchar(max)
)
RETURNS varbinary(256)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result varbinary(256)
SET @Result = EncryptByKey(Key_GUID('MySymmetricKeyName'), @ValueToEncrypt)
-- Return the result of the function
RETURN @Result
END
The Decrypt Function
CREATE FUNCTION Decrypt
(
@ValueToDecrypt varbinary(256)
)
RETURNS varchar(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @Result varchar(max)
SET @Result = DecryptByKey(@ValueToDecrypt)
-- Return the result of the function
RETURN @Result
END
An Example of How to Use Symmetric Keys in a Function
EXEC OpenKeys
-- Encrypting
SELECT Encrypt(myColumn) FROM myTable
-- Decrypting
SELECT Decrypt(myColumn) FROM myTable
As long as you call the OpenKeys stored procedure in the same query as the function, it will work.
Send me a message and I'll get back to you.