AltairCA / EntityFrameworkCore.PostgreSQL.ColumnEncryption

NPGSQL Extension that supports native PostgreSql's [Raw Encryption Functions (encrypt_iv,decrypt_iv with aes-cbc/pad:pkcs)]
15 stars 3 forks source link

Migration of existing data #3

Closed sabihoshi closed 2 years ago

sabihoshi commented 2 years ago

If I annotate an existing column with [NpgsqlEncrypt] and it has existing data, how would I encrypt existing data with the same key that I used? Is there a way to have a migration script for this, or should I be doing it manually with an SQL script?

If it's manual with an SQL script, how should that script look like?

AltairCA commented 2 years ago

Update public."Testings" SET "encrypted" = encode(encrypt_iv( normal::bytea, 'NBJ42RKQ2vQoYFZO','j1C83921vHExVhVp', 'aes-cbc/pad:pkcs'), 'base64') where true;

you can use the above script but remember to replace the password and IV and column and table names according to your context.

In the above example table structure is like this

image

when you prepare the password and IV, it's extracted based on the length that you mentioned in the DbContext.

For example, my full password text is NBJ42RKQ2vQoYFZOj1C83921vHExVhVp1PlOAK6gjbMZI

image

If you mention password(that is going to be used in encryption) length as EncKeyLength.L128, it will extract 128 bits of text from the password text(NBJ42RKQ2vQoYFZOj1C83921vHExVhVp1PlOAK6gjbMZI)

so it will take the first 16 characters from the password text, why 16 because 128/8 is 16. And then it extracts another 16 characters for the IV, for IV it always extracts 16 characters, only the character extraction for the password is gonna vary with the Key Length that you mention in the DbContext.

So for the above password text extracted character will be this,

Password = NBJ42RKQ2vQoYFZO IV = j1C83921vHExVhVp

sabihoshi commented 2 years ago

Thank you for the explanation! How do you generate the password being used? Is it just some random password generated of some certain length? For example, if my key length is EncKeyLength.L256, does that mean I need to use a longer password?

I know there is

var aes = new AesCryptoServiceProvider();
aes.GenerateKey();

Is that any relevant in here? I want to have a password that's done the "proper" way if there is any.

AltairCA commented 2 years ago

Yes, you have to use a longer key for better security. It doesn't matter what method you use to generate the key as long as it's a random string that long enough. Personally, I use LastPass. About the code that you provided, first, you need to set the key size, then get the generated key's byte array and convert that to a string. Maybe this will help.