简体   繁体   中英

encrypt data that is already in mysql table

I have around 2000 rows in my database at the moment, the structure previously was varchar(200). I have since changed the structure to varbinary.

Now when I insert data into my table I use

AES_ENCRYPT('Obama', 'sadhjksauejs') (just an example)

anyway, I want to use AES_ENCRYPT on all the data that is currently in the database, so get the data, encrypt it and put it back into the database, without losing the original data.

what is the best way to do AES_ENCRYPT on all the data that is currently there?

首先,您必须在表encryptedText创建新字段。

UPDATE table SET encryptedText = AES_ENCRYPT(textField,'sadhjksauejs');

There are a couple of things you need to look out for here ...

Yes, VARBINARY is the appropriate data type, however, AES_ENCRYPT is a block-based and will pad your plaintext to the necessary length so your ciphertext will likely be longer than the original. The documentation gives this for calculating the correct column size:

16 * (trunc(string_length / 16) + 1)

You should check that the column is still going to be long enough to hold any value you want to store.

Second, as you are already adding new records in encrypted form you need to make sure that your update statement is restricted to only those records that are still in plaintext.

Once you have taken those things into consideration (and assuming some id or created column) your UPDATE statement will look something like this

UPDATE `yr_table` SET `col1` = AES_ENCRYPT(`col1`,'sadhjksauejs'),
`col2` = AES_ENCRYPT(`col2`,'sadhjksauejs') 
WHERE `id` > whatever;

(ie Not unlike the suggestion by @Sadikhasan)

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