- How to use sequelize with pgcrypto plugin in postgres.
- How to encrypt and decrypt the values of a column using sequelize
- How to use PGP_SYM_ENCRYPT and PGP_SYM_DECRYPT using nodejs and sequelize
2 Answers
I will walk through from starting what steps you need to follow :)
Steps to follow to get pgcrypto plugin into the Schema you are using
Login to Postgres and goto the Schema used. Or If you have
pgadminrunning... goto Schema... right-click... clickQuery Tool.Run this query there to check available plugins in your Postgres:
select * from pg_available_extensionsScroll and check there if
pgcryptois available. If yes, move on to (3), else downloadpgcryptoplugin first.Run another query, this will show what plugins are there with the Schema you have selected in (1):
select * from pg_extensionCheck if
pgcryptois there. If yes, skip to (5); if no, continue to (4)Run this query to bring
pgcryptoplugin from extensions to current Schema supported extension:create extension pgcryptoYou can re-verify by running the query from (3) to check if
pgcryptogot pulled successfully to current Schema supported pluings.
Now we are ready to use pgcrypto in our Nodejs application
For the query which you want to encrypt, make use of
sequelizeto encrypt it. Use below code to modify the text value of that column to encrypted value:query: sequelize.fn("PGP_SYM_ENCRYPT", "data_to_encrypt", "secret_key")When you save the data to the DB using
create, data will be encrypted usingPGP_SYM_ENCRYPTwhich is a method provided by thepgcryptoplugin.To query or decrypt the values now, you can run this query in Postgres:
select PGP_SYM_DECRYPT(colum_name::bytea, 'secret_key') FROM table where PGP_SYM_DECRYPT(column_name::bytea, 'secret_key' LIKE '%search_string%';To decrypt the value in your Node application, use:
sequelize.findAll({ attributes: [ [ sequelize.fn( 'PGP_SYM_DECRYPT', sequelize.cast(sequelize.col('column_name'), 'bytea'), 'secret_key' ), "column_name" ] ] }).then(data => console.log(data))
NOTE: To automate the 1st part (getting extension into Schema), you can use a sequelize raw query, so that you don't have to do it manually each time required.
CREATE EXTENSION IF NOT EXISTS pgcrypto;
1 Comment
I don't have enough reputation to comment on the accepted answer so posting here to help those who might try it and give up because of something quite small.
The accepted answer has a typo that will keep the solution from working.
Step 4 should have "attributes" instead of "attribute"
sequelize.findAll({
attributes: [
[
sequelize.fn(
'PGP_SYM_DECRYPT',
sequelize.cast(sequelize.col('column_name'), 'bytea'),
'secret_key'
),
"column_name"
]
]
}).then(data => console.log(data))