postgresql 中的加密擴充套件外掛pgcrypto用法說明
阿新 • • 發佈:2021-01-21
近期測試了一下postgresql的加密擴充套件外掛pgcrypto的aes加密
安裝加密擴充套件外掛:pgcrypto
在主節點上安裝
create extension pgcrypto;
aes加解密函式簡單介紹
encrypt(data bytea,key bytea,type text) --加密 decrypt(data bytea,type text) --解密
data 是需要加密的資料;type 用於指定加密方法
ASE方式加密:
select encrypt('postgres','abc','aes');
解密:
select convert_from(decrypt('\xd664687424b2806001d0744177284420','aes'),'SQL_ASCII');
建表測試一下
test=# create table user_test(username varchar(20),password varchar(60)); CREATE TABLE test=# insert into user_test values('miya',encode(encrypt('123','hex')); INSERT 0 1 test=# insert into user_test values('kimi',encode(encrypt('456','hex')); INSERT 0 1 test=# select * from user_test; username | password ----------+---------------------------------- miya | a4bf9afce727dbd2805393a86a24096c kimi | 84279efc7942ca7364abcce78db90b0b (2 rows)
解密後可以看出加密前的密碼
test=# select convert_from(decrypt(decode(password,'hex'),'SQL_ASCII') as real_pw,* from user_test; real_pw | username | password ---------+----------+---------------------------------- 123 | miya | a4bf9afce727dbd2805393a86a24096c 456 | kimi | 84279efc7942ca7364abcce78db90b0b
pgcrypto加密還支援很多如md5,bf等詳細可以檢視官方文件
補充:PostgreSQL pgcrypto模組加密解密函式
今天有個需求,要使用資料庫的加密與解密方法,先將部分注意事項寫下備查:
首先要安裝pgcrypto模組,安裝方法進入postgresql的源安裝包資料夾,進入contrib目錄,找到pgcrypto資料夾,進入進行編譯安裝,命令如下:
make USE_PGXS=1 make install
安裝好以後,使用管理員使用者登入使用加解密函式的資料庫,建立extension
create extension pgcrypto ;
pgcrypto 提供了可逆加密演算法:
加密函式
select encrypt('123456','aa','aes'); encrypt ------------------------------------ \x39c3c665757a0ff973b83fb98cc3d63f
解密函式
select convert_from(decrypt('\x39c3c665757a0ff973b83fb98cc3d63f','SQL_ASCII'); convert_from -------------- 123456
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。