Postgresql - 加密jsonb数据

时间:2018-02-21 22:05:03

标签: json postgresql

我在postgres表中有一个jsonb列,我在那里存储json数据。我想以加密格式存储数据,并能够查询并获取纯文本值。有办法吗?

1 个答案:

答案 0 :(得分:3)

使用pgcrypto扩展名。

create extension if not exists pgcrypto;

如果要将现有jsonb列更改为加密列,请将列类型更改为bytea并使用一对扩展程序的加密/解密功能,例如:

create table my_table(id serial primary key, data jsonb);
insert into my_table (data) values
('{"key": "value"}');

alter table my_table
    alter data type bytea 
    using pgp_sym_encrypt(data::text, 'secret_password');

select pgp_sym_decrypt(data, 'secret_password')
from my_table;

 pgp_sym_decrypt  
------------------
 {"key": "value"}
(1 row)