Encrypting and Decrypting Data using the PostgreSQL Server
Before you can encrypt and decrypt data using the PostgreSQL server, you must create the Entrust PSQL Extension. For more information on the functions included in the extension, see Functions provided by the Entrust PostgreSQL Extension.
-
Log in to the PostgreSQL server using the following command:
Copysudo -u postgres psql -
Create the Entrust PSQL Extension using the following command:
CopyCREATE EXTENSION IF NOT EXISTS entrust_psql_extension;
Perform Encryption and Decryption
To encrypt and decrypt data on a PostgreSQL Server using the Entrust PostgreSQL Extension functions, follow these steps:
-
Open Session—This will read the access token and store it in memory using the open_session() function.
-
Fetch Key—Use the get_key() function to fetch the key and store it in cache. This function returns a key handle that will be used to encrypt the data.
-
Encrypt Data—Pass the data and key handle to the encryption function.
-
Decrypt Data—Provide the encrypted data to the decryption function. This function will return the plaintext data.
-
Close Session—Use close_session() to close the current session and clean the key cache.
Example
-
Create a table.
Copycreate table users (name VARCHAR(100), credit_card_details text); -
Open the session using the Access Token file path.
Copyselect open_session('file:///opt/hcs/etc/psql.conf'); -
Fetch the key. refers to the CloudKey that you created. See Creating a CloudKey for PostgreSQL Database Server.
Copyselect get_key('master-key1') as handle \gset -
Encrypt and insert the encrypted data into the table.
Copyinsert into users (name, credit_card_details) values ('John', encrypt_data('my_details', :handle)); -
Decrypt the data.
Copyselect name, decrypt_data(credit_card_details) from users; -
Close the session.
Copyselect close_session();
