Quantcast
Channel: SQL Server Blog
Viewing all articles
Browse latest Browse all 1849

SQL Symmetric Encryption TSQL

$
0
0
Recently my client wanted to create a password vault in SQL database to store SQL Server service account, SQL users and their respective passwords. I used symmetric key to create encryption for the encrypting the password, Find the T-SQL below to accomplish this.

Assumption:-

DB Name - SQLDBA
TableName - SQLAccounts

--********create password encrypted column*********
USE SQLDBA
GO
ALTERTABLE SQLAccounts 
ADD EncryptedSQLPassword varbinary(MAX)NULL
GO

--********Create Master Key*********
USEmaster;
GO
SELECT*
FROMsys.symmetric_keys
WHERE name ='##MS_ServiceMasterKey##';

--**********Create database Key*********
USE SQLDBA
GO
CREATEMASTERKEYENCRYPTIONBYPASSWORD='p@ssw0rd';
GO

--*********Create self signed certificate*********
USE SQLDBA;
GO
CREATECERTIFICATE SQLAccountCertificate
WITHSUBJECT='Protect SQL Password';
GO

--**********Create Symmetric Key***********
USE SQLDBA;
GO
CREATESYMMETRICKEY SQLAccountSymmetricKey
 WITHALGORITHM=AES_128 
 ENCRYPTIONBYCERTIFICATE SQLAccountCertificate;
GO

--*********TSQL to Insert New row with encrypted Password**********
USE SQLDBA;
GO
OPENSYMMETRICKEY SQLAccountSymmetricKey
DECRYPTIONBYCERTIFICATE SQLAccountCertificate;
GO
INSERTINTO SQLAccounts VALUES ('ServerName\Instance','SQLusername',EncryptByKey(Key_GUID('SQLAccountSymmetricKey'),'Password'))
GO
-- Closes the symmetric key
CLOSESYMMETRICKEY SQLAccountSymmetricKey;
GO

--*************TSQL to view decrypted Password**************
USE SQLDBA;
GO

OPENSYMMETRICKEY SQLAccountSymmetricKey
DECRYPTIONBYCERTIFICATE SQLAccountCertificate;
GO
-- Now list the original ID, the encrypted ID 
SELECT*,CONVERT(varchar,DecryptByKey(EncryptedSQLPassword))AS'EncryptedSQLPassword'
FROM dbo.SQLAccounts;
 -- Close the symmetric key
CLOSESYMMETRICKEY SQLAccountSymmetricKey;

--*********TSQL to update the encrypted column*************
USE SQLDBA;
GO
-- Opens the symmetric key for use
OPENSYMMETRICKEY SQLAccountSymmetricKey
DECRYPTIONBYCERTIFICATE SQLAccountCertificate;
GO
UPDATE SQLAccounts
SET EncryptedSQLPassword =EncryptByKey(Key_GUID('SQLAccountSymmetricKey'),Password)
FROM dbo.SQLAccounts;
GO
-- Closes the symmetric key
CLOSESYMMETRICKEY SQLAccountSymmetricKey;
GO

Viewing all articles
Browse latest Browse all 1849

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>