Security

AWS KMS Envelope Encryption vs HashiCorp Vault vs Postgres pgcrypto: Storing BVN and NIN PII Under NDPR

O
Oluwaseun AlabiTechnical Director
November 21, 202615 min read
AWS KMS Envelope Encryption vs HashiCorp Vault vs Postgres pgcrypto: Storing BVN and NIN PII Under NDPR

Storing Bank Verification Numbers (BVN) and National Identification Numbers (NIN) in plaintext will sink your NDPR audit and invite devastating breach liability. We evaluate AWS KMS Envelope Encryption, HashiCorp Vault Transit, and Postgres pgcrypto to help you balance cryptographic isolation, latency, and compliance requirements.

Most engineering teams building fintech apps in Nigeria handle sensitive identity payload—specifically Bank Verification Numbers (BVN), National Identification Numbers (NIN), and phone numbers tied to tier-3 KYC—by turning on PostgreSQL Transparent Data Encryption (TDE) on RDS and calling it a day.

That strategy fails basic regulatory scrutiny under the Nigeria Data Protection Act (NDPA) enforced by the Nigeria Data Protection Commission (NDPC). TDE protects your block storage at rest if someone physically walks out of an AWS data center with an NVMe drive. It does absolutely nothing to protect PII against SQL injection, compromised database read replicas, exposed staging dumps, or rogue backend engineers running unfiltered SELECT * FROM users; queries in production.

Under NDPR compliance requirements, sensitive personal data requires explicit access logging, cryptographic isolation, and an operational mechanism for data minimization and crypto-shredding (implementing the 'Right to be Forgotten' without violating CBN financial record retention laws).

When we audit core banking engines and payment applications at Neobot Tech, we focus on field-level encryption (FLE). Instead of encrypting the entire disk, you encrypt individual table columns before or during the write path.

Here is a practical breakdown comparing the three dominant field-level encryption patterns used by African technical teams: Postgres pgcrypto, AWS KMS with Envelope Encryption, and HashiCorp Vault (Transit Secrets Engine).


Option 1: Application-Managed Postgres pgcrypto

pgcrypto is a built-in PostgreSQL extension providing cryptographic functions for database-level encryption. Using functions like pgp_sym_encrypt() and pgp_sym_decrypt(), your application passes raw bytes to Postgres, which encrypts the payload before writing it to disk.

-- Inserting encrypted BVN into user table using pgcrypto
INSERT INTO user_identities (id, user_id, bvn_encrypted)
VALUES (
  gen_random_uuid(),
  'usr_94a021b3',
  pgp_sym_encrypt('22233344455', current_setting('app.encryption_key'))
);

The Reality of Using pgcrypto in Production

The advantage of pgcrypto is zero additional infrastructure overhead. You do not need to run an external daemon or manage third-party API rate limits.

However, its security architecture contains structural flaws for sensitive compliance workloads:

  1. Key Leakage in Postgres Logs: If your DBA turns on statement_logging = 'all' to debug slow queries, your symmetric encryption key is written in cleartext to log files whenever pgp_sym_encrypt() runs with a inline string key.
  2. High CPU Contention: Cryptographic primitives (AES-256-GCM or PGP symmetric encryption) are CPU-bound. Offloading column encryption to Postgres forces your database primary node to burn CPU cycles on crypto math instead of servicing transactional queries like Postgres FOR UPDATE SKIP LOCKED locks.
  3. Key Rotation Failure: Rotating a master secret in pgcrypto requires rewriting every single row in the database table under an exclusive table lock, causing massive write amplification and downtime on large datasets.

Use pgcrypto only if you are bootstrapping on a single-node database with zero budget and under 5,000 active customer records.


Option 2: AWS KMS with Envelope Encryption

AWS Key Management Service (KMS) combined with the AWS Encryption SDK implements Envelope Encryption. In this model, AWS KMS holds a Master Key (KMS Key) that never leaves AWS Hardware Security Modules (HSMs).

Instead of sending your raw BVN payload to AWS KMS over HTTP (which introduces severe network latency and API cost spikes at scale), your application calls KMS to generate a local Data Encryption Key (DEK).

Your application uses the unencrypted DEK to encrypt the customer's BVN locally in application memory using AES-256-GCM, stores the encrypted payload alongside the encrypted DEK in Postgres, and wipes the raw DEK from local memory immediately.

Diagram showing AWS KMS Envelope Encryption workflow for BVN storage

Architectural Flow for AWS KMS Envelope Encryption

  1. The user inputs their 11-digit BVN during onboarding.
  2. Node.js/Go backend requests a Data Encryption Key from AWS KMS via GenerateDataKey API.
  3. AWS KMS returns two keys: a plaintext DEK and a ciphertext DEK (encrypted by the KMS Master Key).
  4. Application encrypts the raw BVN using the plaintext DEK.
  5. Application discards the plaintext DEK.
  6. Application saves bvn_ciphertext, bvn_blind_index (a salted HMAC hash for lookups), and encrypted_dek into PostgreSQL.
// Node.js implementation of AWS KMS Envelope Encryption for BVN storage
import { KmsKeyringNode, buildClient, Commitments } from '@aws-crypto/client-node';
import crypto from 'crypto';

const { encrypt, decrypt } = buildClient(
  Commitments.ENFORCE_COMMIT_WITH_DECRYPT_COMMIT
);

const generatorKeyId = process.env.AWS_KMS_KEY_ARN;
const keyring = new KmsKeyringNode({ generatorKeyId });

export async function encryptPII(bvnString, userId) {
  const context = { 
    purpose: 'NDPR_KYC_STORAGE',
    owner: userId 
  };

  // Encrypt raw BVN locally using data key generated from KMS
  const { result } = await encrypt(keyring, Buffer.from(bvnString), {
    encryptionContext: context
  });

  // Generate a deterministic blind index for exact-match database queries
  const blindIndex = crypto
    .createHmac('sha256', process.env.BLIND_INDEX_SALT)
    .update(bvnString)
    .digest('hex');

  return {
    encryptedPayload: result.toString('base64'),
    blindIndex
  };
}

Why AWS KMS Envelope Encryption Wins for Cloud-Native Teams

AWS KMS Envelope Encryption offloads cryptographic workloads entirely to application instances, which scale horizontally. Your database stores inert base64 strings.

More importantly, AWS KMS provides absolute audit trails via AWS CloudTrail. Every single decryption request for a customer's BVN emits an immutable log entry stating which IAM role accessed which key at what exact millisecond. If a rogue developer accesses customer PII, CloudTrail gives your compliance team forensic evidence required by NDPR auditors.

For details on AWS Key Management Service architecture, review the official AWS Encryption SDK Documentation.


Option 3: HashiCorp Vault (Transit Secrets Engine)

HashiCorp Vault is the industry standard for multi-cloud secrets management. Its Transit Secrets Engine acts as "Encryption as a Service."

Unlike envelope encryption where your application handles local data keys, your application sends raw PII directly to Vault over a TLS-encrypted RPC/HTTP endpoint. Vault encrypts the payload in memory and returns a ciphertext string formatted as vault:v1:8gFjW9m.... Your application stores this ciphertext string in PostgreSQL.

The Operational Overhead of Self-Hosted Vault

Vault offers complete independence from cloud vendor lock-in. You can run Vault clusters across cloud providers or local data centers.

However, Vault introduces significant operational failure modes for local engineering teams:

  • Network Overhead on Write/Read Paths: Every database read requiring a BVN lookup requires a synchronous HTTP round-trip to your Vault cluster. If your application decrypts 50 records in a list view, naive sequential API calls to Vault will add hundreds of milliseconds of latency.
  • Unseal Operation Risks: Vault starts in a sealed state. If your Vault node restarts due to memory pressure or infrastructure failover, your backend engineering team must manually unseal it using threshold keys (Shamir's Secret Sharing) unless auto-unseal via AWS KMS/Azure Key Vault is configured.
  • High Maintenance Overhead: Running a highly available, multi-node Raft-backed Vault cluster requires dedicated platform engineering resources.

For comprehensive configuration patterns, consult the HashiCorp Vault Transit Documentation.


Head-to-Head Architectural Comparison

| Criteria | Postgres pgcrypto | AWS KMS Envelope Encryption | HashiCorp Vault (Transit Engine) | | :--- | :--- | :--- | :--- | | Cryptographic Isolation | Low (Keys live in DB memory/logs) | High (Master key sealed in AWS HSM) | Highest (Master key isolated in Vault memory) | | NDPR Audit Log Quality | Poor (Database log parsing required) | Excellent (Native CloudTrail integration) | Superior (Detailed audit devices/streams) | | Latency Overhead | Medium (DB CPU impact) | Near Zero (< 2ms, local memory crypto) | High (Synchronous network hop to Vault) | | Key Rotation Complexity | Severe (Requires full table rewrites) | Seamless (Automatic KMS rotation + DEK versioning) | Seamless (Vault key version pointers) | | Crypto-Shredding Support | Difficult (Manual record deletion) | Medium (Key revocation per tenant context) | Easy (Targeted key deletion by customer ID) | | Infrastructure Cost | Free ($0 added cost) | Low ($0.03 per 10k requests + $1/mo key) | High (Requires dedicated HA compute nodes) |


Solving the Exact-Match Lookup Problem: Blind Indexing

When you encrypt a column like bvn using strong AES-256-GCM encryption, the ciphertext output changes on every invocation due to random initialization vectors (IVs). This prevents attackers from detecting patterns, but it breaks SQL queries like:

-- THIS IS IMPOSSIBLE WITH AES-GCM ENCRYPTION
SELECT * FROM users WHERE bvn = '22233344455';

Many inexperienced teams solve this by switching to deterministic encryption (ECB mode or static IVs). Never do this. Deterministic encryption exposes your database to statistical analysis and frequency attacks.

Instead, pair field-level encryption with a Blind Index.

A Blind Index is a one-way cryptographic hash of the PII generated using a secret salt separate from your primary database encryption keys (typically HMAC-SHA256). You store the blind index in an indexed column next to the encrypted field.

CREATE TABLE user_identities (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id VARCHAR(64) NOT NULL UNIQUE,
    bvn_ciphertext TEXT NOT NULL,
    bvn_blind_index VARCHAR(64) NOT NULL -- HMAC-SHA256 hash
);

CREATE INDEX idx_identities_bvn_blind ON user_identities(bvn_blind_index);

When a customer inputs their BVN to verify an account, your application computes HMAC-SHA256(input_bvn, BLIND_INDEX_SALT) and executes a point lookup against bvn_blind_index. Once the record is identified, you decrypt bvn_ciphertext using AWS KMS or Vault.

This pattern preserves search capabilities while maintaining zero-knowledge properties on stored encrypted fields. Similar patterns are vital when designing resilient financial systems, such as building robust payment reconciliation engines in Go.


Architectural Recommendations by Use Case

Use AWS KMS Envelope Encryption If:

  • You are hosted on AWS (RDS, ECS, EKS, Lambda).
  • You need to minimize network latency on read-heavy workflows.
  • You want an audit log that satisfies NDPR compliance officers without building custom logging infrastructure.
  • Verdict: This is the default recommendation for 90% of Nigerian fintech startups.

Use HashiCorp Vault Transit Engine If:

  • You run a multi-cloud or hybrid infrastructure (e.g., core banking on-premise at a local data center in Lagos with edge services on GCP/AWS).
  • You require strict cryptographic decoupling where cloud providers must have zero physical access to encryption keys.
  • You have a dedicated platform/security engineering team to manage Vault cluster operational health.

Use Postgres pgcrypto If:

  • You are building an early-stage internal MVP or side project.
  • You operate under extreme budget constraints where managing KMS keys or Vault nodes is unviable.
  • Warning: Plan an architectural migration away from pgcrypto before launching to production users handling tier-3 KYC data.

Frequently Asked Questions

Does stored PII encryption fulfill NDPR compliance by itself?

No. Encryption at rest is one requirement of NDPR (Article 2.6). Compliance also mandates explicit user consent collection, data minimization, strict role-based access control (RBAC), published privacy policies, and demonstrable audit logging showing who accessed what data and why.

Can we store raw BVN strings if we hash them using bcrypt?

No. Passwords can be hashed using one-way functions like bcrypt or argon2id because you only ever need to verify equality. Identification credentials like BVN and NIN often need to be decrypted to be passed securely to licensed NIBSS processors or identity verification partners. One-way hashing makes retrieval impossible.

How does field-level encryption impact dynamic virtual account assignments?

Dynamic virtual accounts rely on fast database lookups linking incoming bank transfers to customer profiles. Using blind indexing alongside KMS envelope encryption ensures that virtual account assignment queries hit indexed btree fields without decrypting the customer's PII until transaction confirmation receipts are generated. For a deeper discussion on payment rail security, see our technical analysis on why static virtual accounts are a security liability.

What happens if we lose our Master Key in AWS KMS or HashiCorp Vault?

If a Master Key is permanently destroyed or deleted, your encrypted database columns are mathematically unrecoverable. For production setups, always enable AWS KMS Deletion Protection and enforce strict IAM policies preventing kms:ScheduleKeyDeletion without multi-party approval.


Selecting the right field-level encryption pattern is not just about checking a box for NDPR auditors—it dictates your system's operational resilience during a breach. If you are building high-throughput payment applications or core banking infrastructure in West Africa, favor AWS KMS Envelope Encryption for cloud workloads or Vault Transit for hybrid deployments. Keep cryptographic keys out of your database engines, pair your encrypted columns with blind indexes, and never store cleartext KYC credentials in application memory longer than necessary to service a request.

Neobot Engineering Standard

Every system deployed by Neobot Tech incorporates enterprise baseline practices. We continuously audit our database topologies, REST API query paths, and frontend modular bundles to prevent latency spikes and ensure top-tier security posture.

Tags:#Security#NDPR#AWS KMS#PostgreSQL#Fintech#Cryptography#HashiCorp Vault

Discussion

Comments Coming Soon

We are currently migrating our discussion engine to a new real-time database schema. Check back shortly to join the conversation.