Create Extension
First, if the extension is not present, it is created with the following command.
1 | CREATE EXTENSION pgcrypto; |
The functions we will use;
1 2 | PGP_SYM_ENCRYPT('The value to be entered in the column:','AES_KEY') PGP_SYM_DECRYPT(column_name::bytea,'AES_KEY') |
Example:
We create the table with the help of the following script.
1 | Create table den(age integer,password varchar(255)); |
The column we want to encrypt is inserted as follows.
1 | insert into den values(21,PGP_SYM_ENCRYPT(‘AAA’,‘AES_KEY’)); |
To view without encryption:
1 | select age,pgp_sym_decrypt(password::bytea,‘AES_KEY’) from den; |
To view with encryption:
1 | select * from den; |
If requested, the password in the database can be updated as follows.
1 2 3 4 | UPDATE den SET password=( PGP_SYM_ENCRYPT(‘sss’,‘AES_KEY’) )WHERE age=21; |
If you do not want the password to be plain text in the database, you can use the chkpass extension.
You can find the details about the chekpass in the artilce named “How To Encrypt a Column(Like Password) with chkpass On PostgreSQL”