sql 암호화/복호화
/*
Step 1 : Mater Key 생성
현재 DB의 마스터 키를 생성을 합니다.
Create Master Key Encryption By Password = 'Khdj0215'
*/
/*
Step 2 : 인증서 생성
현재 DB에 대칭키에 사용할 인증서를 생성을 합니다.
Create Certificate EncryptKeyForPassword With Subject = 'This is used for using Symmetric Key'
*/
/*
Step 3 : Symmetric Key 생성
현재 DB에 인증서를 이용해서 대칭키를 생성을 합니다.
Create Symmetric Key PasswordEncryptionKey With Algorithm = AES_256 Encryption By Certificate EncryptKeyForPassword
*/
/*
Step 4 : Table 생성
Test할 수 있는 임의의 Table을 생성을 합니다.
Create Table UserTable (
UserID int Identity(1,1) Not Null Primary Key Clustered,
UserName NVarchar(100) Not Null,
UserPassword VarBinary(128) Not Null
);
*/
/*
Step 5 : 프로시저 생성
암호를 암호화해서 저장하는 저장 프로시저 InsertUser 를 생성을 합니다.
Create Proc InsertUser
@UserName NVarchar(100),
@UserPassword Char(16),
@Code NVarchar(20)
AS
Begin
Open Symmetric Key PasswordEncryptionKey Decryption By Certificate EncryptKeyForPassword;
Insert into dbo.UserTable([UserName],[UserPassword])
Values (@UserName, ENCRYPTBYKEY(Key_Guid('PasswordEncryptionKey'), @UserPassword, 1, @Code));
Close Symmetric Key PasswordEncryptionKey
End
암호화된 암호를 복호화해서 정보를 제공하는 저장 프로시저 LoadUser를 생성을 합니다.
Create Proc LoadUser
@UserName NVarchar(100),
@Code NVarchar(20)
AS
Begin
Select [UserName], CONVERT(Char(16), DecryptBykeyAUtoCert(cert_ID('EncryptKeyForPassword'), Null, [UserPassword], 1, @Code)) AS UserPassword
From UserTable Where UserName = @UserName
End
*/
exec InsertUser '김덕중', '1111', ''
exec LoadUser '김덕중', ''
select * from UserTable
truncate table UserTable