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.

  1. Log in to the PostgreSQL server using the following command:  

    Copy
    sudo -u postgres psql
  2. Create the Entrust PSQL Extension using the following command: 

    Copy
    CREATE 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:

  1. Open Session—This will read the access token and store it in memory using the open_session() function.

  2. 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.

  3. Encrypt Data—Pass the data and key handle to the encryption function.

  4. Decrypt Data—Provide the encrypted data to the decryption function. This function will return the plaintext data.

  5. Close Session—Use close_session() to close the current session and clean the key cache.

Example

  1. Create a table.

    Copy
    create table users (name VARCHAR(100), credit_card_details text);
  2. Open the session using the Access Token file path.

    Copy
    select open_session('file:///opt/hcs/etc/psql.conf');
  3. Fetch the key. refers to the CloudKey that you created. See Creating a CloudKey for PostgreSQL Database Server.

    Copy
    select get_key('master-key1') as handle \gset
  4. Encrypt and insert the encrypted data into the table.

    Copy
    insert into users (name, credit_card_details) values ('John', encrypt_data('my_details', :handle));
  5. Decrypt the data.

    Copy
    select name, decrypt_data(credit_card_details) from users;
  6. Close the session.

    Copy
    select close_session();