I am working with Credit Card numbers and I am looking for my Instead Of trigger to "Instead of" inserting in the original CCNum field and CCExp field, to do an insert in the Encrypted Fields called CCNum_enc and CCExp_enc and make the CCNum field and CCExp field NULL.
Also let's say someone changes their expiration date on their CC, I want the trigger to update that field. The original fields will stay null but the encrypted fields will update with the new expiration date.
This is the code of what I am trying to do...
ALTER trigger [dbo].[TR_m_payments_ENC]
on [dbo].[m_payments_ENC] instead of INSERT, update
as
BEGIN
SET NOCOUNT ON;
Open symmetric key sk_employees decryption by certificate cert_sk_admin
insert into [m_payments_ENC]
(
CCNum, CCExp, CCNum_en, CCExp_en, CCNum_l4, OtherStuff--, CCNum_IDX
)
select
NULL,
NULL,
encryptbykey( key_guid('sk_employees'), CCNum, 1, HashBytes('SHA1', CONVERT( varbinary, payID))),
encryptbykey( key_guid('sk_employees'), CCExp, 1, HashBytes('SHA1', CONVERT( varbinary, payID))),
RIGHT([inserted].[CCNum], 4),
[inserted].OtherStuff
from inserted
UPDATE [m_payments_ENC]
set CCNum = NULL,
CCExp = NULL,
CCNum_en= encryptbykey( key_guid('sk_employees'), [inserted].CCNum, 1, HashBytes('SHA1', CONVERT( varbinary, [m_payments_ENC].payID))),
CCExp_en= encryptbykey( key_guid('sk_employees'), [inserted].CCExp, 1, HashBytes('SHA1', CONVERT( varbinary,[m_payments_ENC].payID))),
CCNum_l4 = RIGHT([inserted].[CCNum], 4),
OtherStuff = [inserted].OtherStuff,
from [m_payments_ENC], inserted
WHERE [m_payments_ENC].payID = inserted.payID
and inserted.CCExp is not null
CLOSE SYMMETRIC KEY sk_employees
end