As the first task we will create a symmetric key and a certificate as below.
USE Staff;
GOCREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Passwordabcd';
GO
CREATE CERTIFICATE Prod_Cert WITH SUBJECT = 'Key Protection';
GO
CREATE SYMMETRIC KEY My_Key WITHKEY_SOURCE = 'This is the symmetric key',
ALGORITHM = AES_256,
IDENTITY_VALUE = 'This is the symmetric key'
ENCRYPTION BY CERTIFICATE Prod_Cert;
GO
-- Create a column in which to store the encrypted data.
ALTER TABLE dbo.Employee
ADD EncryptedAge varbinary(128);
GO
USE Staff;
Values in the column are encrypted as below.
GO
OPEN SYMMETRIC KEY My_Key
DECRYPTION BY CERTIFICATE Prod_Cert;
UPDATE dbo.Employee
SET EncryptedAge
= EncryptByKey(Key_GUID('My_Key'), 'my new value');
GO
OPEN SYMMETRIC KEY My_Key
DECRYPTION BY CERTIFICATE Prod_Cert;
UPDATE dbo.Employee
SET EncryptedAge
= EncryptByKey(Key_GUID('My_Key'), 'my new value');
GO
Use below query to decrypt the value
OPEN SYMMETRIC KEY My_Key
You can get the decrypted value as below
DECRYPTION BY CERTIFICATE Prod_Cert;
GO
SELECT Name, EncryptedAge
AS 'Encrypted Age',
CONVERT(varchar, DecryptByKey(EncryptedAge))
AS 'Decrypted Age'
FROM dbo.Employee;
GO
SELECT Name, EncryptedAge
AS 'Encrypted Age',
CONVERT(varchar, DecryptByKey(EncryptedAge))
AS 'Decrypted Age'
FROM dbo.Employee;
GO
No comments:
Post a Comment