TDE normally protects the data encryption key (pg_encryption/key.bin) as you initialize the cluster, but you can choose to disable key wrapping, leaving the key unprotected, for example, for testing or demo purposes. If you disabled key wrapping and now want to protect the key, update the encryption settings in the postgresql.conf file, as shown in this example.
Enable key wrapping with a passphrase
This example shows you how to add a passphrase-based protection mechanism or key wrapping to your data encryption key (key.bin).
Store the passphrase in a file accessible by initdb named
pass.bin:Important
This example stores the passphrase in plaintext, a method you should only use for testing or demonstration purposes. In production environments, don't store your passphrase in a file. See Using a passphrase for alternative methods.
echo "<passphrase>" > /var/lib/postgresql/pass.bin
Use OpenSSL to encrypt the existing
key.bindata encryption key with the stored passphrase and save the encrypted file askey.bin.WRAP:cat $PGDATA/pg_encryption/key.bin | openssl enc -e -aes-128-cbc -pbkdf2 -pass file:/var/lib/postgresql/pass.bin -out $PGDATA/pg_encryption/key.bin.WRAP
Create a backup of the unwrapped data encryption key named
key.bin.NOWRAPin case you need to roll back to the original configuration:cp $PGDATA/pg_encryption/key.bin $PGDATA/pg_encryption/key.bin.NOWRAP
Replace the existing data encryption key with the wrapped version:
cp $PGDATA/pg_encryption/key.bin.WRAP $PGDATA/pg_encryption/key.bin
Create a backup of the existing configuration file named
postgresql.conf.NOWRAPin case you need to roll back to the original configuration:cp $PGDATA/postgresql.conf $PGDATA/postgresql.conf.NOWRAP
Modify the
data_encryption_key_unwrap_commandvalue of thepostgresql.conffile with the new command:sed -i "s|data_encryption_key_unwrap_command.*|data_encryption_key_unwrap_command = 'openssl enc -d -aes-128-cbc -pbkdf2 -pass file:/var/lib/postgresql/pass.bin -in \"%p\"'|" $PGDATA/postgresql.conf
Create a backup of the modified
postgresql.conffile that includes the key wrapping namedpostgresql.conf.WRAP:cp $PGDATA/postgresql.conf $PGDATA/postgresql.conf.WRAP
Restart your database cluster to populate the updated data encryption key configuration:
pg_ctl start
Confirm the cluster starts successfully and the new key wrapping configuration works, then remove the rollback backups.
key.bin.NOWRAPis a plaintext copy of your data encryption key, so leaving it on disk defeats the purpose of wrapping the key:rm $PGDATA/pg_encryption/key.bin.NOWRAP $PGDATA/postgresql.conf.NOWRAP