To implement database storage encryption in MySQL, you can use several methods depending on your requirements. Here are the common approaches with examples:
Transparent Data Encryption (TDE)
MySQL Enterprise Edition supports TDE, which encrypts data files at rest. This ensures that data stored on disk is encrypted and decrypted automatically when accessed.
Example:
-- Enable TDE (requires MySQL Enterprise)
INSTALL PLUGIN keyring_file SONAME 'keyring_file.so';
SET GLOBAL keyring_file_data='/var/lib/mysql-keyring/keyring';
ALTER INSTANCE ROTATE INNODB MASTER KEY;
Encryption at Rest with Filesystem/OS Tools
If TDE is not available, you can encrypt the data directory using OS-level tools like LUKS (Linux) or BitLocker (Windows). This encrypts the entire storage volume.
Example (Linux LUKS):
cryptsetup luksFormat /dev/sdX
cryptsetup open /dev/sdX mysql_encrypted
mkfs.ext4 /dev/mapper/mysql_encrypted
mount /dev/mapper/mysql_encrypted /var/lib/mysql
Column-Level Encryption
Encrypt specific sensitive columns using MySQL functions like AES_ENCRYPT and AES_DECRYPT.
Example:
-- Insert encrypted data
INSERT INTO users (username, sensitive_data)
VALUES ('john', AES_ENCRYPT('credit_card_number', 'encryption_key'));
-- Retrieve and decrypt data
SELECT username, AES_DECRYPT(sensitive_data, 'encryption_key') FROM users WHERE username = 'john';
InnoDB Tablespace Encryption
MySQL supports encrypting individual InnoDB tablespaces. This requires the keyring plugin.
Example:
-- Create an encrypted tablespace
CREATE TABLE encrypted_table (id INT, data VARCHAR(255))
ENCRYPTION='Y';
For managed MySQL services, Tencent Cloud Database for MySQL provides built-in encryption features, including TDE and SSL/TLS for data in transit. It simplifies encryption setup and management compared to self-hosted solutions.
Example (Tencent Cloud MySQL TDE):
For column-level encryption, Tencent Cloud MySQL supports the same MySQL functions (AES_ENCRYPT, etc.), ensuring compatibility with existing applications.