How To Encrypt and Decrypt Data using Sql Server

2.1 ) For get how many certificate and symetric key

select * from sys.certificates
select * from sys.symmetric_keys

2.2)  now one by one remove it

drop symmetric key SymmetricKey1
drop certificate Certificate1
drop master key

2.3) now cretae first master key

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'PassWord';

2.4) cretae certificate and symertic key
2.4.1) GO
CREATE CERTIFICATE Certificate1
WITH SUBJECT = 'Protect Data';
2.4.2)
CREATE SYMMETRIC KEY SymmetricKey1
 WITH ALGORITHM = AES_128
 ENCRYPTION BY CERTIFICATE Certificate1;

-----------------------------Encrypt Data-----------------------------

OPEN SYMMETRIC KEY SymmetricKey1
DECRYPTION BY CERTIFICATE Certificate1;
GO
select EncryptByKey (Key_GUID('SymmetricKey1'),'Hello')

GO
-- Closes the symmetric key
CLOSE SYMMETRIC KEY SymmetricKey1;

---------------------------Decrypt data--------------------------------

OPEN SYMMETRIC KEY SymmetricKey1
DECRYPTION BY CERTIFICATE Certificate1;
SELECT  CONVERT(varchar, DecryptByKey(EncryptByKey (Key_GUID('SymmetricKey1'),'Hello') ))
CLOSE SYMMETRIC KEY SymmetricKey1

Post a Comment

0 Comments