Column-level encryption with pgcrypto

Column-level encryption with pgcrypto protects selected fields inside a self-hosted PostgreSQL database, but the keys, queries and search design decide whether it protects anything. This page explains the trade-offs before you build.

On this page

When pgcrypto column encryption fits a self-hosted PostgreSQL database

A team that must protect a few specific fields, such as national identifiers, bank account numbers or health notes, while keeping the rest of the schema queryable needs field-level protection rather than a change to the whole database. The pgcrypto extension provides that option inside PostgreSQL. According to the PostgreSQL documentation for the extension, it offers symmetric and public-key PGP functions, which wrap and unwrap data with a passphrase or a key pair, along with lower-level raw cipher functions for teams that need precise control over the algorithm and mode. Confirm which functions and algorithms your PostgreSQL version and extension build expose before you design around them, because the available set can change between releases.

pgcrypto protects the stored value of each encrypted column. It does not hide the table structure, row counts, column names or the sizes of encrypted values, and it does not stop a database administrator from reading data while the server is running and the key is supplied. Any query that decrypts a value sends the key or passphrase to the server, where it can appear in statement text, logs and monitoring if statement logging is verbose. Disk encryption protects against stolen drives and backups copied off the host, but every process with database access still sees plaintext. Column encryption fits when the threat includes insiders or compromised application roles reading a specific subset of fields, and when the team can keep keys outside the database. It is a weaker fit when most of the schema needs filtering, sorting or full-text search, because encrypted values cannot be indexed in a useful way.

If the application already runs in a service that can hold keys securely, encrypting in the application before the value reaches PostgreSQL often gives stronger separation. The database then never receives the key, and the same key-handling design applies to every consumer of the data. Choose the database-side approach when many applications write to the same tables, when a central team must control decryption through SQL functions, or when the application cannot be changed quickly. Before committing, ask the team to write down who may decrypt each field, where the key is stored, how a key is rotated without rewriting every row, and which queries must still run on encrypted fields. Those answers decide whether pgcrypto is the right layer.

pgcrypto column encryption options: PGP symmetric, PGP public-key and raw functions

This table compares the three main pgcrypto function families by key model, who can decrypt, and what the database sees in plaintext during each call. Use it to narrow the design before you test, and confirm exact function names and options against the pgcrypto documentation for your PostgreSQL major version.

OptionKey model and who can decryptPlaintext exposure during the callSuits teams that
PGP symmetric-key functions (pgp_sym_encrypt, pgp_sym_decrypt)One passphrase encrypts and decrypts. Anyone who holds the passphrase can read the column, including every database session that supplies it.The passphrase and the plaintext both pass through the SQL statement, so they can appear in query text, logs and statement statistics unless logging is controlled.Need a simple field-level control for a small number of columns and can keep the passphrase outside SQL text.
PGP public-key functions (pgp_pub_encrypt, pgp_pub_decrypt)Encryption uses a public key that the database can hold. Decryption needs the matching private key and its passphrase, so writers and readers can be separated.Plaintext reaches the database during encryption, and the private key and passphrase reach it during decryption. Keep decryption in narrow, reviewed roles.Need separate write and read authority, such as collecting sensitive values without letting every application role decrypt them.
Low-level cipher functions (encrypt, decrypt, encrypt_iv, decrypt_iv, digest, hmac)Raw block cipher calls with a key and optional IV. The team owns key handling, IV generation, padding and mode choices.The key and plaintext are visible in the statement, and misuse of modes or IVs can weaken protection without any error.Have in-house cryptography review and need to match an existing format or external system. Usually a poor fit for ad hoc column work.
Key held by the applicationThe application or service fetches or derives the key at runtime and sends it with each call, so the key lives in process memory, not in stored SQL.Plaintext and key still reach PostgreSQL for each call unless encryption happens entirely in the application.Own the application code and want the database never to hold the key at rest.
Key in a secrets managerA dedicated secrets service issues the passphrase or key to approved workloads under access policy and audit. Rotation is handled by that service.Keys are fetched at runtime and must still be passed into the call, so statement logging and monitoring tools need the same controls.Already run a secrets platform and need central rotation, access logs and separation of duties. Confirm the integration pattern with your team.
Passphrase written directly in the queryKey material sits in the SQL text, so every caller and log that captures statements can see it.Highest exposure: the key appears in query text, pg_stat_statements output, slow query logs and client-side history.Rarely a sound choice for production. Use only for a short test where the data and logs are disposable.
Search and indexing effectRandomized PGP output means equal plaintext values produce different ciphertext, so equality lookups and standard indexes on the encrypted column do not work.Searching requires decrypting rows, or storing a separate keyed hash or blind index designed by your team.Can accept scanning or application-side filtering, or can design and review a blind index for specific lookups.

How a pgcrypto write and read move keys and ciphertext

The write starts in the application, which sends the plaintext value and a key reference to PostgreSQL. The database runs the pgcrypto call and stores only ciphertext in the table. On read, the key is supplied again and decryption happens inside the database process. Check which boundaries the plaintext and the key cross, since the database server process, its logs, and backups each see different material. The key store should sit outside the database host.

Key and plaintext cross the database boundary during each encrypted write and read.

Setting up pgcrypto columns in a self-hosted cluster

This sequence takes a column-encryption design from package check to tested round trips and log review, so the encrypted fields work in your cluster and nothing sensitive leaks through the database's own logs. Each step ends with a check that the team can record as evidence.

  1. Confirm the extension is approved and installed

    The platform or database team checks that the pgcrypto extension ships in the PostgreSQL packages your organization uses on each node, including replicas and any staging clusters, and that your security team has approved it for the data classes in scope. Run SELECT * FROM pg_available_extensions WHERE name = 'pgcrypto'; on every node, then record the installed version and the approval reference. The step is complete when every node reports the same version and the approval is on file. Confirm the exact package name and support status with your PostgreSQL distribution, since packaging differs between Linux distributions and container images.

  2. Choose the key model and key store

    The security architect decides whether keys are held in the application, in a secrets manager such as OpenBao, or in an HSM your organization already operates, and whether one key protects many columns or each tenant or table has its own. Write down who can read key material, where it is stored at rest and how it reaches the session that calls the functions. The output is a one-page key model signed off by the data owner. Do not let the decision default to a key stored in a database table or a parameter that appears in every query, because the database then holds both the ciphertext and the means to read it.

  3. Define encrypted columns and their data types

    The data owner and developers list each column to be encrypted, then set its storage type. pgp_sym_encrypt returns bytea, so the column type changes from text or numeric to bytea, and any constraint, default or index that assumed the original type must be reviewed. Build a table of column, original type, new type, who reads it and which queries depend on it. The step is complete when a migration script creates the new columns in a staging database and the application's test suite passes against them. Columns that need lookup or range search should be listed separately, because they need the design work in the indexing section below.

  4. Plan key rotation and re-encryption

    The security and database teams agree how often keys rotate, how a new key is introduced, and how existing rows are re-encrypted under it. Rotation with pgcrypto usually means decrypting with the old key and encrypting with the new one in a controlled batch job, so the plan must cover batch size, locking, progress tracking and a rollback path. Ask your team to test the job on a copy of production data and measure how long it takes on that copy before scheduling it. The step is complete when a dry run re-encrypts a sample table and every row decrypts correctly afterward.

  5. Load functions with a least-privileged role

    The database administrator creates the extension in a schema that application roles cannot write to, then grants EXECUTE on only the wrapper functions the application needs, not on the raw pgcrypto functions. Encryption and decryption run in a dedicated owner role, and application roles receive no direct SELECT on the base table's sensitive columns where a view or function can do the job. Verify the grants by connecting as each application role and attempting a direct decrypt call and a plain select on the encrypted column. The step is complete when the unauthorized attempts fail and the authorized path succeeds, and the results are saved with the change record.

  6. Test encrypt and decrypt round trips

    The QA team writes test cases that insert known values, read them back through the approved path, and compare the results byte for byte, including empty strings, nulls, multi-byte characters and the largest values the column will hold. They also confirm that a wrong key or a corrupted ciphertext produces an error rather than silent garbage. Run the suite on a restored copy of a production-like database, not on a development instance with synthetic data only. The output is a test report that shows every round trip passes and every failure case is caught.

  7. Restore a backup and test decryption

    The backup team restores a recent backup into a separate environment and confirms that encrypted columns decrypt with the keys held in the key store, which proves the key store and the backup set are both recoverable. Include the key store in the recovery drill, since ciphertext without its key is unreadable. The step is complete when the restored database returns the expected plaintext for a sample of rows and the restore procedure is recorded with its date and operator. Your backup policy should state how keys are backed up separately from data, and who may authorize that restore.

  8. Review statement logging and monitoring for key material

    The operations and security teams review the PostgreSQL logging settings, including log_statement, log_min_duration_statement and any statement capture by monitoring or proxy tools, to confirm that passphrases and keys do not appear in logs, slow query captures or dashboards. Calls that pass a key as a literal are the usual source of leakage, so the team checks whether applications bind keys as parameters and whether pg_stat_statements normalizes them. Search recent logs for a known test key after running the round-trip tests. The step is complete when the search returns nothing and the logging configuration is saved to version control.

pgcrypto column encryption key and log exposure risks

Column-level encryption protects a field only as long as the key, the plaintext and the surrounding logs stay out of reach. The six risks below are the places where pgcrypto deployments most often leak, and each one needs its own control and its own check.

Keys inside SQL text

When an application calls pgp_sym_encrypt or pgp_sym_decrypt with the passphrase written into the statement, that passphrase travels as part of the SQL text. Statement logging, log_min_duration_statement output and pg_stat_statements can capture it, depending on settings. Bind the key as a parameter from the application side and confirm in your own cluster which statement text is logged and who can read those logs. Parameter binding does not stop a driver or proxy from logging the query.

Authentication docs

Plaintext in server memory

pgcrypto runs encryption and decryption inside the database server process, so the plaintext value and the key exist in server memory for the duration of each call. A control on disk or in transit does not cover this window. Limit which roles can call the decryption functions, keep decrypted results narrow in the SELECT list, and ask your team whether any memory inspection or core dump policy applies to database hosts.

Keys stored beside the data

If the passphrase or private key sits in a table, a configuration file on the database host, or the same backup set as the ciphertext, an attacker who gets the backup gets the plaintext. Keep keys in a separate secrets service such as OpenBao, with its own access policy and its own backups. Confirm that database dumps, base backups and WAL archives never include key material, and that restore tests use separately stored keys.

Privileged roles reading logs and dumps

Superusers, members of pg_read_all_data and anyone with read access to log files or dump files can often see the same material as the application. Pair column encryption with least-privilege roles so the decryption function is executable only by the application role. Review who can read PostgreSQL log directories, log shipping destinations and backup repositories, and confirm each reader has a documented need.

Authentication methods

Old ciphertext after key rotation

Rotating a pgcrypto key does not re-encrypt existing rows. Old ciphertext stays encrypted under the previous key, so a retired key must remain available for as long as those rows exist, or the rows must be re-encrypted in a planned batch. Record a key version next to each encrypted value, write a re-encryption job, and test that rows encrypted under the old key still decrypt after rotation. Old copies in backups also need a retention decision.

Application logs of decrypted values

The most common leak happens after decryption, when application code writes the returned value to an application log, an error tracker or a debug trace. Database controls cannot see this path. Review logging middleware, exception handlers and ORM debug output, mask fields that pgcrypto returns, and test failure paths with dummy values to confirm nothing sensitive reaches the log pipeline. Confirm this in your own application stack.

Encrypting in the database or in the application, by situation

When one PostgreSQL cluster serves several applications, the database administrators, the application teams and the backup operators all have access paths to the same tables. pgcrypto encryption done in SQL protects the stored value from anyone reading files or dumps, but any role that can run pgp_sym_decrypt with the key can read plaintext. The practical question is therefore who controls the key material and how it reaches the database session. Keys passed as literals in SQL can surface in statement logs, pg_stat_statements and client tooling, so the key should arrive through a controlled path, and the design should be explicit about which roles may call decrypt functions.

  • Key location: Keep the key in a secrets manager you operate, and pass it through a short-lived session setting or a function that only a dedicated role can execute.
  • Decrypt rights: Grant execute on decryption functions to named roles only, and keep them off PUBLIC.
  • Audit view: Log who changed the key-handling functions and who ran them, and confirm that statement logging does not capture key values.
  • Shared-tenant risk: A DBA with superuser rights can read function bodies and session data, so the design should state that limit openly.
  • When to move to the application: If other applications or administrators must never see plaintext, application-side encryption keeps decryption outside the shared database.

Confirm with your database team how statement logging and monitoring tools handle function arguments before you go live.

What to confirm before relying on pgcrypto columns

Column-level encryption moves trust from the database engine to the code, keys and operating procedures around it. The cards below are questions to answer in your own environment before you rely on pgcrypto for sensitive fields, because each one changes whether the design holds up under review.

pgcrypto version and support status

Confirm which pgcrypto build your packaging provides for your PostgreSQL major version, and whether that major version is still supported. PostgreSQL 14 support ends November 12, 2026, and PostgreSQL 15 support ends November 11, 2027, so a column design built now may outlive its database version. Ask your distribution or vendor which pgcrypto release ships with each version, and plan the upgrade path at the same time as the database upgrade.

Versioning policy

Cipher and key length acceptance

Ask your audit and compliance reviewers whether they accept the symmetric and public-key algorithms, modes and key lengths your functions use, and whether they expect a specific algorithm list. Check the cipher defaults in the pgcrypto docs for your version, because options such as the S2K iteration count and the cipher-algorithm parameter are set per call and are easy to leave at weak values. Record the chosen settings in your design document so reviewers can trace each column to an approved setting.

Key store custody requirements

Confirm where keys are held, who can read them, and how they are rotated and revoked. A key stored in a table, a configuration file or an application environment variable sits next to the ciphertext it protects. Ask whether your custody policy requires an external key manager, split knowledge or dual control, and whether your team can rotate a key without re-encrypting the whole table in a single outage window.

Archiving docs

Replica and backup handling of ciphertext

Confirm how streaming replicas, base backups, WAL archives and logical copies carry encrypted columns. Ciphertext replicates and backs up like any other data, so a stolen backup still contains the encrypted values, but it is useless without keys stored elsewhere. Check whether your restore tests prove that the keys needed to decrypt are restored with the data, and whether a backup restored into a separate environment can be decrypted only by the authorized key holders.

High availability docs

Query performance on encrypted columns

Measure the cost of the queries you run, because decryption happens per row inside the database. A filter or sort on a decrypted value cannot use a normal B-tree index on the stored ciphertext, since the ciphertext changes with each encryption. Test the queries that matter at realistic row counts, and confirm whether you need blind indexes, hashed search tokens or application-side filtering for lookups, and whether those choices meet your privacy review.

Application and ORM key handling

Confirm that your application and ORM can pass key material without writing it to query text, logs or statement statistics. A key passed as a literal in a SQL statement can appear in server logs, connection pooler logs, slow-query logs and monitoring tools. Check whether your ORM uses bind parameters for the key, whether debug logging is off in production, and whether your team has a tested way to pass keys through a session setting or a prepared statement without exposing them.

What buyers ask about cost, effort and running pgcrypto columns

What drives the cost of pgcrypto column encryption?

The main cost drivers are the number of encrypted fields, how those fields are queried, how many application code paths touch them, and how the keys are stored and released. Each encrypted field adds schema changes, a migration that re-writes existing rows, and tests for every read and write path. Search requirements add the most design work, because equality lookups need a deterministic companion value or blind index that must be designed and reviewed. Key store integration adds cost when the keys must come from an existing vault or HSM. Ask any partner for a quote that lists the fields, the query patterns, the application repositories affected and the key source as separate line items, and that states which items are one-time and which recur, such as key rotation runs and retesting after schema changes.

How long does a scoped pgcrypto engagement take?

Duration depends mainly on the number of encrypted fields, the number of application services that read or write them, and whether existing data must be migrated in place. A small set of fields in one application with no search requirement is far less work than a schema with many sensitive columns used by several services. Key store integration and approval of the key custody model often take longer than the SQL itself, because they involve other teams. The migration window for existing rows, and the time to prove that backfill and rollback work on a copy of production data, also set the schedule. No duration is given here; the written scope should state the schedule and the assumptions behind it.

What does the internal team need to provide?

A column encryption project needs three groups of people from your side. Schema owners decide which columns are encrypted, confirm which queries must still work, and approve any change to types or constraints. Key custodians define who may hold or release the encryption keys, where they live, and how access is logged. Application developers identify every code path that reads or writes the protected fields, and they must accept changes to how those fields are passed into SQL. Security and compliance staff should review the threat model early so the design matches what they must show an assessor. Plan time for these people before the build starts, not after it.

Can our internal team do pgcrypto column encryption without a partner?

Yes, a team with strong PostgreSQL and application skills can implement pgcrypto without an outside partner, and many do. The hard parts are not the function calls. They are the key design, the search design, the migration of existing rows, and the tests that prove no plaintext reaches logs, statistics views or query text. Teams that have not handled these before often find gaps only after go-live. A partner is most useful as a second design review, as a hands-on implementer for a fixed scope, or as an independent tester of the finished setup. Weigh your team's experience with key management and PostgreSQL logging against the schedule you need.

How is key rotation handled after go-live?

Key rotation with pgcrypto means re-encrypting stored values under a new key, and the process must be designed before go-live. Plan a way to tag each ciphertext with the key version it used, so old and new data can coexist during a rotation. Then define a batch job that reads, decrypts with the old key, encrypts with the new key and writes back, with checkpoints so it can resume after failure. Confirm how keys are retrieved by the application at runtime and how revoked keys are removed from every system that cached them. Rotation runs and the retest after each change recur, so ask a partner to price them as ongoing work and to state who runs them.

Does pgcrypto alone meet a compliance requirement?

No single tool meets a compliance requirement by itself. pgcrypto provides cryptographic functions inside PostgreSQL, but a compliance assessment looks at the whole system: how keys are generated, stored, rotated and restricted, which roles can see plaintext, how access and key use are logged, how backups handle the protected values, and how the design is documented. Column encryption also does not cover data in memory, temporary files or application logs unless those are handled separately. Ask your assessor which controls they expect to see, and map each one to evidence your system produces. DeployOpen prepares systems, controls and evidence for compliance assessments, but independent auditors and certification bodies issue the assessment outcome.

What should we ask for in a pgcrypto quote?

Ask for a written scope that lists each encrypted column, its data type, and the queries it must support, including equality search, range search and sorting. Ask how keys are sourced, where they are stored, who can release them, and how that is logged. The quote should name the application services that change, the tests that prove plaintext does not reach PostgreSQL logs or statistics, and the migration and rollback plan for existing rows. Confirm the deliverables, such as configuration, SQL, runbooks and evidence, and what the partner needs from your team. Finally, ask what is one-time and what recurs, including rotation support, and whether a retest is included after changes.

How DeployOpen scopes and delivers pgcrypto column encryption

DeployOpen plans pgcrypto column encryption as part of a self-hosted PostgreSQL platform in your infrastructure. We start by agreeing which fields are protected, where keys are held and how the application calls the database, then build, test and document the design before handing it over.

How we scope

  • Inventory the columns that need field-level protection and the queries, reports and jobs that read them today.
  • Record the key custody model, including who may access key material and where it is stored.
  • Agree in writing which encryption functions, indexes and search patterns are in scope before work starts.

How we build

  • Implement pgcrypto functions in SQL or application code according to the agreed encryption design and key handling.
  • Check that keys do not appear in query text, statement logs, error messages or monitoring output.
  • Test search, sorting and indexing behavior on encrypted columns against the queries your teams actually run.

How we hand over

  • Deliver written documentation covering the encryption design, key lifecycle, decryption paths and known limits.
  • Provide test evidence and runbooks for key rotation, access review and recovery of encrypted data.
  • Walk your database, security and application teams through the design so they can operate it independently.

How we support

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
  • Ongoing support, upgrades and continuous testing are available as a retainer after handover.
  • Confirm with your team whether the retainer covers changes to encrypted columns as application code evolves.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.