简体   繁体   中英

How to encrypt/decrypt data in some columns of a table and when a new record gets inserted it should also get encrypt

i know like this to insert a new record

INSERT INTO dbo.Customer_data (Customer_id, Customer_Name, Credit_card_number)
VALUES (25665, 'mssqltips4', EncryptByKey( Key_GUID('SymmetricKey1'), CONVERT(varchar,'4545-58478-1245') ) ); 

but i want to insert a new record with a normal insert statement which should get encrypted. ex:

INSERT INTO dbo.Customer_data (Customer_id, Customer_Name, Credit_card_number)
VALUES (25665, 'mssqltips4','4545-58478-1245') ) );       

Few months ago I had similar situation. A table containing personal data need to have some of the columns encrypted, but the table is used in legacy application and have many references.

So, I you can create a separate table to hold the encrypted data:

CREATE TABLE [dbo].[Customer_data_encrypted]
(
    [customer_id] PRIMARY KEY -- you can create foreign key to the original one, too
   ,[name] VARBANRY(..)
   ,[cretit_card_numbe] VARBINARY(..)
);

Then create a INSTEAD OF INSERT UPDATE DELETE trigger on the original table.The logic in the trigger is simple:

  1. on delete, delete from both tables
  2. on update/insert - encrypt the data and insert in the new table; use some kind of mask to the original table (for example *** or 43-****-****-**** )

Then, perform a initial migration to move the data from the original table to the new one and then mask it.

Performing the steps above are nice because:

  1. every insert/update to the original table continue to works
  2. you can create the trigger with EXECUTE AS OWNER in order to have access to the symmetric keys and perform changes directly in the T-SQL statement without opening the certificates or by users who have not access to them
  3. in all reads references you are going to get mask data, so you are not worried for breaking the application critically
  4. having trigger gives you ability to easy create and changes information

It depends on your environment and business needs because for one of the tables I have stored the encrypted value as new column, not separate table. So, choose what is more appropriate for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM