PGP Symmetric Encrypt Decrypt Roundtrip
pgp_sym_encrypt seals text into a bytea with a passphrase and pgp_sym_decrypt opens it; random session keys make identical plaintexts encrypt differently.
Code
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- 对称 PGP 加密:口令派生密钥,密文是 bytea,库里不落明文
SELECT pgp_sym_decrypt(
pgp_sym_encrypt('recovery codes', 'opensesame'),
'opensesame'
) AS roundtrip_plain;
-- PGP 会话密钥与 IV 随机:同一明文两次加密得到不同密文
SELECT pgp_sym_encrypt('same message', 'opensesame')
<> pgp_sym_encrypt('same message', 'opensesame') AS ciphertexts_differ;
-- 常见落库形态:密文列 + 口令只留在应用侧
CREATE TEMP TABLE sealed_files (
name text PRIMARY KEY,
body bytea NOT NULL
);
INSERT INTO sealed_files
SELECT 'notes-2026q4', pgp_sym_encrypt('rotate token quarterly', 'opensesame')
UNION ALL
SELECT 'notes-2026q3', pgp_sym_encrypt('expired, keep sealed', 'opensesame');
-- 读取端用同一口令解密;口令错误时抛 WrongKeyException(Wrong key or corrupt data)
SELECT
name,
pgp_sym_decrypt(body, 'opensesame') AS opened
FROM sealed_files
ORDER BY name;The operational picture
The file runs SELECT / INSERT / CREATE statements, touching sealed_files.
sealed_files gets built by this very file as a session-local temp table — no setup has to come before it, and the end of the session takes it back.
What the statements actually assemble: an ORDER BY that fixes the output order; a UNION stitching together the result sets of separate queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Putting it to use
Nothing outside the file is needed: the session-local tables it touches (sealed_files) are created by the file itself — point it at a scratch database and run the whole thing.
Core lines
INSERT INTO sealed_files
SELECT 'notes-2026q4', pgp_sym_encrypt('rotate token quarterly', 'opensesame')
UNION ALL
SELECT 'notes-2026q3', pgp_sym_encrypt('expired, keep sealed', 'opensesame');
SELECT pgp_sym_decrypt(
pgp_sym_encrypt('recovery codes', 'opensesame'),
'opensesame'
) AS roundtrip_plain;
SELECT pgp_sym_encrypt('same message', 'opensesame')
<> pgp_sym_encrypt('same message', 'opensesame') AS ciphertexts_differ;
Interactive Tools for This Topic
FAQ
- What objects does the SQL involve?
- `sealed_files`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.