Well, we are moving one step forward for data encryption and decryption, I have already described some of the essential topics in this area which are mandatory before implementing this step. If you want to go backward, have a look at series of article on this topic at below given link.
Once you have SMK and DMK, you will have choice to go for Certificates, Asymmetric key, Symmetric key. Scope of this article is use of certificate. Let us start our journey.
Certificate is a kind of Asymmetric encryption with some additional metadata. In Asymmetric encryption data got encryption by two different methods but mathematically both are same. You can use “CREATE CERTIFICATE” T-SQL for creating new or use existing certificate.
–create new cerfiticate
CREATE CERTIFICATE ADV
ENCRYPTION BY PASSWORD =‘$qlhub’
WITH SUBJECT =‘ADVENTUREWORKS CERTIFICATE’,
START_DATE=’09/14/2009′, –IF NOT PROVIDED, CURRENT DATE IS START DATE
EXPIRY_DATE=’09/13/2015′— IF NOT PROVIDED, ONE YEAR AFTER START_DATE IS EXPIRY_DATE
I have observed that people are really very cautious about the data and used to take regular backup of data but not that much cautious for certificates. I HIGHLY recommend taking backup of your certificate as soon as you create it, so let us seeing the script of that.
BACKUP CERTIFICATE ADV
TO FILE = ‘d:\ADV.CER’
WITH PRIVATE KEY
ENCRYPTION BY PASSWORD=‘$qlhub’,
DECRYPTION BY PASSWORD=‘$qlhub’
Generally you think of restore command as soon as you finish backup. Let me tell you that there is no restore certificate command as you can restore your existing certificate from your backup file itself from CREATE CERTIFICATE command only. Have a look.
–LET US drop just created certificate and restore it from
–.cer file so that we are sure that certificate is created
DROP CERTIFICATE ADV
–restore from file
CREATE CERTIFICATE ADV
Once you create certificate and take a backup of it, now, you are ready to encrypt your data with certificate and decrypt it whenever it is needed.
DECLARE @Text nvarchar(max)
DECLARE @TextEnrypt varbinary(128)
DECLARE @TextDecrypt nvarchar(max)
SET @Text=N’hi, this is first certificate test, created by Ritesh Shah’
SELECT @Text AS ‘ORIGINAL TEXT’,@TextEnrypt AS ‘Encrypted Text’,@TextDecrypt as ‘Decrypted Text’
Hope you have enjoyed this small tour.