I am trying to write a stored procedure to decrypt some data encrypted by a Symmetric Key that’s encrypted with an Asymmetric Key with a password.
OPEN SYMMETRIC KEY requires a string literal for the password so I had to do a work around with EXEC sp_executesql. Is there a better way to do this?
DECLARE @open nvarchar(200), @close nvarchar(200)
SET @open = 'OPEN SYMMETRIC KEY skey DECRYPTION BY ASYMMETRIC KEY akey WITH PASSWORD = ' + quotename(@password,'''') + ';';
SET @close = 'CLOSE SYMMETRIC KEY skey;';
EXEC sp_executesql @open
SELECT [TransactionID],Convert(varchar(max),DECRYPTBYKEY([EncryptedText])) as DecryptedText FROM [dbo].[TestTable];
EXEC sp_executesql @close
If you execute it with the wrong password it throws up the following errors:
Msg 15466, Level 16, State 1, Line 1
An error occurred during decryption.
Msg 15315, Level 16, State 1, Line 1
The key 'skey' is not open. Please open the key before using it.
Should I just wrap EXEC sp_executesql @open in a TRY ... CATCH and return NULL or is there a (more) elegant way of handling this?
EDIT: What’s the best way to handle someone calling this procedure with an incorrect password?
EXAMPLE of using keys, check your data and code:
For proper logging of wrong password decryption attempts try the following example, play with variable
@password: