我的 postgres 表中有一个 jsonb 列,用于存储 json 数据。我想以加密格式存储数据并能够查询并获取纯文本值。有办法做到吗?
使用pgcrypto扩展程序。
create extension if not exists pgcrypto;
Run Code Online (Sandbox Code Playgroud)
如果要将现有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)
Run Code Online (Sandbox Code Playgroud)