PG中使用pgcrypto给敏感数据进行加密
简介
除了RLS来限制用户访问数据的安全策略外,pg中还允许对行数据进行加密,这样对于用户来说某些关键的数据也是起到了限制访问的作用。
示例
数据加密首先需要安装pgcrypto扩展:
1 2 | postgres=# create extension pgcrypto ; CREATE EXTENSION |
这里简单演示下如何进行加密。
新建表:
1 2 | postgres=# create table t1(id int,name text,password text); CREATE TABLE |
我们先使用简单的MD5进行加密:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | postgres=# insert into t1 values(2,'xxt',md5('lhr')); INSERT 0 1 postgres=# insert into t1 values(3,'lhr',md5('lhr')); INSERT 0 1 postgres=# select * from t1; id | name | password ----+------+------------------------------------ 2 | xxt | 3996643de967b80174e48fb45d7227b1 3 | lhr | 3996643de967b80174e48fb45d7227b1 (3 rows) postgres=# select * from t1 where password=md5('lhr'); id | name | password ----+------+---------------------------------- 2 | xxt | 3996643de967b80174e48fb45d7227b1 3 | lhr | 3996643de967b80174e48fb45d7227b1 (2 rows) |
使用 md5 加密后,如果两个用户的密码相同,那么 md5 加密后的密码也一样,如果破解了一个 md5 密码,那么很容易破解 md5 值相同的密码。
我们使用pgcrypto来对该表的password列进行加密,这里使用md5进行加密:
1 2 3 4 5 6 7 8 9 10 11 | postgres=# insert into t1 values(0,'bitt',crypt('123456',gen_salt('md5'))); INSERT 0 1 postgres=# postgres=# insert into t1 values(1,'bill',crypt('123456',gen_salt('md5'))); INSERT 0 1 postgres=# select * from t1; id | name | password ----+------+------------------------------------ 0 | bitt | $1$KWk2U/BG$4Utofcc0QUQTeLWmfQ2Zy/ 1 | bill | $1$DJQShqgZ$1PaLxbUmDYRL1L0dkDDqF1 (2 rows) |
验证:返回t说明输入的密码正确。
1 2 3 4 5 6 7 8 9 10 11 12 | postgres=# SELECT (password = crypt('123456',password)) AS pwmd5 FROM t1 ; pwmd5 ------- t t (2 row) postgres=# select * from t1 where password = crypt('123456',password); id | name | password ----+------+------------------------------------ 1 | bill | $1$DJQShqgZ$1PaLxbUmDYRL1L0dkDDqF1 0 | bitt | $1$KWk2U/BG$4Utofcc0QUQTeLWmfQ2Zy/ (2 rows) |
虽然 bitt,bill使用相同的密码,但经过 crypt() 函数加密后,加密后的密码值不同,显然,这种加密方式要比 md5 安全。