postgres服务之加密

数据中往往会出现一些敏感字段,例如电话,邮箱等,这时候有需求进行加密保存

目前可以实现的方式有两种

方式一:这种方法,aes的加密方法不支持aes-192,不支持aes-256

#使用encrypt加解密
#加密保存
insert into test2(username,email) values('liulm7',encrypt('[email protected]','aa','aes-128'));

postgres=# select * from test2 where username='liulm7';
 username |                               email                                | phone | address 
----------+--------------------------------------------------------------------+-------+---------
 liulm7   | \x39162fadc179498413b75b69bc65c98d19e454a0c67bd644118ab9df3c7b49ef |       | 
(1 row)

#解密查看
postgres=# select username,convert_from(decrypt(email::bytea,'aa'::bytea,'aes-128'),'utf8') as email from test2 where username='liulm7';
 username |       email       
----------+-------------------
 liulm7   | [email protected]
(1 row)

方式二:

#使用pgp_sym_encrypt加密
insert into test2(username,email) values('pgp_sym',pgp_sym_encrypt('[email protected]','abc','cipher-algo=aes256, compress-algo=2, compress-level=9'));
insert into test2(username,email) values('pgp_sym',pgp_sym_encrypt('[email protected]','abc','cipher-algo=aes256, compress-algo=2, compress-level=9'));
#解密查看
postgres=# select username,pgp_sym_decrypt(email::bytea,'abc') from test2 where username='pgp_sym';
 username | pgp_sym_decrypt  
----------+------------------
 pgp_sym  | [email protected]
 pgp_sym  | [email protected]
(2 rows)

参数说明:

cipher-algo  加密算法
compress-algo 压缩类型,使用的压缩算法,取值 0,1(zip),2(zlib)
compress-level 压缩比,级别越高压缩比越大,速度也会更慢,压缩级别(0~9)
convert-crlf 是否在加密的时候将\n装换为\r\n,在解密的时候将\r\n转换为\n
disable-mdc 是否使用SHA1保护数据
sess-key 是否使用单独的会话密钥
s2k-mode 使用哪一种S2K算法
s2k-count 使用S2K的迭代次数
s2k-digest-algo 在s2k中使用哪种摘要算法
s2k-cipher-algo 要用哪种密码来加密独立的会话密钥
unicode-mode 是否将文本数据从数据库内部编码转为UTF-8并返回

猜你喜欢

转载自www.cnblogs.com/mmyy-blog/p/11643523.html