How to fill encrypted columns in database using SqlBulkCopy?

c# database encryption sqlbulkcopy sql-server

Question

I'm using SqlBulkCopy and System.Data.Datatable to insert data into my database. I'm doing something like this:

var table = new DataTable();

// Creating table schema
var newRow = table.NewRow();
newRow["FirstName"] = Parser.Parse(values[0])
newRow["LastName"] = Parser.Parse(values[1])
...
newRos["SSN"] = //here I need to encrypt by db certificate value[5] before set it to this row value

And simple copy to db code:

using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction))
{
    bulkCopy.BatchSize = 100;
    bulkCopy.DestinationTableName = "dbo.Member";
    try
    {    
        bulkCopy.WriteToServer(table);
    }
    catch (Exception)
    {
        transaction.Rollback();
        connection.Close();
        throw;
    }
}

Of course I can set encrypted column later using a stored procedure in the database, but I want to do this in one transaction. Is it possible to encrypt string value using my certificate from the database in code?

Thanks in advance!

Accepted Answer

As I see this, you can choose one of the following options (which should be both easy to implement):

Do the encryption in your C# code

Since you have all the data there, you can make the encryption there using .NET Framework relevant classes. You can test it and make sure you get the same result.

Use AFTER INSERT trigger

After adding the value, you'll modify and add the encrypted data. The trigger will be part of the same transaction. Just use CREATE TRIGGER statement to create a new trigger, check if the value is NULL and then put the encrypted value using SQL statements.

For Example:

CREATE TRIGGER [dbo].[myTrigger]
   ON  [dbo].[Members] 
   AFTER INSERT
AS 
BEGIN
    SET NOCOUNT ON;
    UPDATE Members
    SET [EncryptedSSN] = EncryptByKey(Key_GUID('SSN_Key'), inserted.SSN)
    FROM inserted 
    INNER JOIN dbo.Members On inserted.id = Members.id
END 

Hope this helps.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow