Security

Encrypting BVNs under NDPR: AWS KMS vs HashiCorp Vault Transit vs Postgres pgcrypto

A
Adebayo FalojuPrincipal Systems Architect
November 3, 202614 min read
Encrypting BVNs under NDPR: AWS KMS vs HashiCorp Vault Transit vs Postgres pgcrypto

Storing raw 11-digit BVNs or NINs in plain text PostgreSQL tables triggers immediate NDPC regulatory penalties. We evaluate AWS KMS, HashiCorp Vault Transit Engine, and Postgres pgcrypto across latency, cost, key rotation, and NDPR compliance readiness.

The Nigeria Data Protection Commission (NDPC) does not care about your startup sprint deadlines. When an independent auditor inspects your PostgreSQL schema during an NDPR compliance verification, finding 11-digit Bank Verification Numbers (BVNs) or National Identity Numbers (NINs) stored as unencrypted VARCHAR(11) columns triggers immediate regulatory penalties under Section 39 of the Nigeria Data Protection Act 2023. Worse, unencrypted database dumps exported during staging syncs or developer testing immediately expose citizen PII to third-party engineers.

Yet, many backend teams in Lagos default to bad patterns. Some hash BVNs using SHA-256 without salt, rendering the data irreversible when they later need to verify the user against a payment gateway API like Paystack or Prembly. Others drop a static ENCRYPTION_SECRET environment variable into their Node.js .env file and run symmetric AES-256-CBC directly in application code—storing the key right alongside the codebase in deployment pipelines.

To satisfy NDPR requirements without destroying database query performance or introducing single-point-of-failure key leaks, you need a proper cryptographic architecture. In this article, we evaluate three primary technical approaches for encrypting sensitive PII at rest in Nigerian payment engines: AWS KMS Envelope Encryption, HashiCorp Vault Transit Engine, and PostgreSQL's built-in pgcrypto extension.

Diagram showing PII flow between application server, KMS key management service, and PostgreSQL database

Option 1: Application-Level Envelope Encryption with AWS KMS

Envelope encryption separates data key management from key encryption. Instead of sending raw BVNs over the network to AWS KMS for encryption—which introduces unbearable HTTP network round-trips for batch processing—you request a localized Data Encryption Key (DEK) from AWS KMS. The KMS Key Management Service returns a plaintext DEK and an encrypted version of that same DEK (wrapped using your KMS Customer Master Key).

Your application server uses the plaintext DEK to locally encrypt the user's BVN with AES-256-GCM, immediately wipes the plaintext DEK from RAM, and stores both the ciphertext BVN and the encrypted DEK inside PostgreSQL.

Here is how this implementation looks in TypeScript using the official @aws-sdk/client-kms library:

import { KMSClient, GenerateDataKeyCommand, DecryptCommand } from "@aws-sdk/client-kms";
import { createCipheriv, createDecipheriv, randomBytes } from "crypto";

const kms = new KMSClient({ region: "eu-west-1" });
const KMS_KEY_ID = process.env.AWS_KMS_KEY_ARN!;

interface EncryptedPayload {
  encryptedBvn: string;
  encryptedDek: string;
  iv: string;
  authTag: string;
}

export async function encryptBvn(bvn: string): Promise<EncryptedPayload> {
  // Request a fresh Data Encryption Key from AWS KMS
  const command = new GenerateDataKeyCommand({
    KeyId: KMS_KEY_ID,
    KeySpec: "AES_256",
  });
  const { Plaintext, CiphertextBlob } = await kms.send(command);
  if (!Plaintext || !CiphertextBlob) throw new Error("KMS DEK generation failed");

  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", Buffer.from(Plaintext), iv);
  
  let encrypted = cipher.update(bvn, "utf8", "hex");
  encrypted += cipher.final("hex");
  const authTag = cipher.getAuthTag().toString("hex");

  return {
    encryptedBvn: encrypted,
    encryptedDek: Buffer.from(CiphertextBlob).toString("base64"),
    iv: iv.toString("hex"),
    authTag,
  };
}

The Operational Reality of AWS KMS in Nigeria

AWS KMS provides clean audit logging via AWS CloudTrail, satisfying NDPR requirements for tracking access to cryptographic keys. You can specify key policies that deny access to developers, guaranteeing that even database administrators cannot read BVNs without explicit IAM permission to call kms:Decrypt.

The main drawback is network geography. AWS has no primary region in Nigeria (the Lagos Local Zone lacks native KMS hardware security modules). If your core backend runs on AWS eu-west-1 (London) or af-south-1 (Cape Town), calling GenerateDataKey per user onboarding adds roughly 40ms to 120ms of latency over transoceanic fiber. While acceptable for single user registration flows, it degrades performance during bulk payroll disbursements or batch account verification runs.

Learn more about configuring key policies in the AWS KMS Developer Guide.

Option 2: Centralized Secret & Crypto Engine with HashiCorp Vault Transit Engine

HashiCorp Vault takes a radically different approach with its Transit Secrets Engine. Rather than handling encryption keys inside application memory, Vault acts as Cryptography-as-a-Service. Your application sends the plaintext BVN to Vault's REST API, and Vault returns a secure ciphertext string. Vault manages key storage, hardware security module (HSM) backing, and key rotation internally.

This architecture completely divorces cryptographic key management from your application logic and database schema. When you migrate infrastructure—such as moving from AWS EKS to $140/mo Hetzner Bare Metal: Slashing SaaS Infrastructure Costs by 73% for a Nigerian Logistics Engine—your encryption infrastructure remains entirely self-contained within your private network.

Why Vault Transit Engine Excels for NDPR Compliance

  1. Zero-Trust Key Distribution: Application pods never touch raw encryption keys. Even if an attacker achieves Remote Code Execution (RCE) on your Node.js app server, they can only request encryptions/decryptions through Vault policies. They cannot exfiltrate the master private key file.
  2. Built-in Key Rotation without Database Rewrites: Vault uses versioned key ring keys (e.g., vault:v1:8xKw9...). When you rotate keys, old ciphertexts remain readable by older key versions (v1), while all new encryptions use v2. You can re-wrap stored ciphertexts asynchronously via background jobs without decrypting PII into application RAM.
  3. Local Deployment Latency: Self-hosting HashiCorp Vault on a dedicated bare-metal server co-located in local data centers or on low-latency private networks drops decryption overhead down to < 2ms per request.

For implementation specifications and policy configurations, review the official HashiCorp Vault Transit Engine documentation.

Option 3: In-Database Encryption using Postgres pgcrypto

If you prefer to isolate cryptographic logic directly inside your database queries, PostgreSQL offers the pgcrypto extension. Using functions like pgp_sym_encrypt() and pgp_sym_decrypt(), encryption and decryption occur natively inside SQL execution plans.

-- Enabling the extension
CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- Inserting encrypted BVN
INSERT INTO user_profiles (user_id, encrypted_bvn)
VALUES (
  'usr_8923114',
  pgp_sym_encrypt('22299887711', current_setting('app.bvn_encryption_key'))
);

-- Decrypting BVN for payment processing
SELECT 
  user_id, 
  pgp_sym_decrypt(encrypted_bvn::bytea, current_setting('app.bvn_encryption_key')) AS bvn
FROM user_profiles
WHERE user_id = 'usr_8923114';

This pattern eliminates external HTTP or RPC calls entirely during encryption and decryption, offering superior raw throughput. As discussed in our detailed evaluation of Why Western Identity Tools Destroy SME SaaS Margins: Building a Custom Postgres Session Engine in Node.js, keeping workload operations directly inside Postgres can significantly simplify early-stage engineering stacks.

The Operational Hazards of pgcrypto

Despite its simplicity, pgcrypto introduces severe security and architectural liabilities:

  • Database CPU Exhaustion: Asymmetric PGP or heavy symmetric AES encryption in Postgres is CPU-bound. Offloading cryptographic operations onto your primary database instance degrades overall query throughput and connection pool availability during peak traffic hours.
  • Master Key Leakage in Query Logs: If keys are passed directly as literal SQL strings (e.g., pgp_sym_encrypt('22233344455', 'my-secret-key')), unredacted database slow-query logs, pg_stat_statements, or proxy mirrors will record the raw key in plaintext.
  • Weak Key Isolation: The entity holding database write access also holds access to execute decryption functions. If an attacker gains read-only replica access or standard SQL injection entry points, they can invoke pgp_sym_decrypt() directly inside the database session.

Technical & Regulatory Comparison Matrix

The following evaluation matrix breaks down key engineering and compliance parameters across all three options:

| Criteria | AWS KMS (Envelope) | HashiCorp Vault Transit | Postgres pgcrypto | | :--- | :--- | :--- | :--- | | Key Isolation | Excellent (Keys sealed in KMS HSM) | Excellent (Keys sealed inside Vault) | Poor (Key lives in DB query / app env) | | Latency Overhead | Medium (40-100ms API network call) | Ultra-Low (<3ms if deployed locally) | Zero network overhead (In-DB CPU) | | Cost Profile | $1/mo per CMK + $0.03/10k API calls | Free (Open Source) or HCP Enterprise | Free (Uses DB CPU cores) | | Key Rotation Complexity | High (Requires application re-wrap) | Low (Automatic versioning with re-wrap API) | Painful (Requires full table re-encryption) | | NDPR Audit Log Quality | Immutable AWS CloudTrail logs | Immutable Vault Audit Log streams | Limited (Standard Postgres log files) | | DB CPU Impact | Zero (Handled on App Server) | Zero (Handled by Vault Cluster) | High (Increases query CPU usage) | | Blast Radius of DB Breach | Safe (DB dump yields useless ciphertext) | Safe (DB dump yields useless ciphertext) | Vulnerable if app session config leaks |

Recommendation & Use-Case Breakdown

Selecting the right encryption layer depends on your application's transaction volume, compliance budget, and underlying hosting infrastructure:

1. Early-Stage Startups & Single-Instance MVPs

Recommendation: AWS KMS (Envelope Encryption) If your stack runs on AWS (ECS, App Runner, or EC2) and your engineering team lacks dedicated DevOps engineers, AWS KMS is the safest default. Envelope encryption ensures raw keys never sit in repository environment files. CloudTrail automatically generates immutable access logs required during NDPR compliance audits. The latency penalty is trivial for low-throughput onboarding routes.

2. Multi-Cloud, Bare-Metal, or High-Volume Fintech Engines

Recommendation: HashiCorp Vault Transit Engine If you host infrastructure on bare-metal providers like Hetzner or run high-frequency virtual account assignment engines, centralized Vault instances are vastly superior. Vault provides zero-trust key isolation, eliminates transoceanic cloud latency, and allows seamless, non-disruptive key rotations. You get complete hardware ownership without paying per-request API micro-charges to public cloud providers.

3. Strictly Avoid pgcrypto for Core PII in Production

pgcrypto should only be used for low-risk, internal administrative tooling where infrastructure budget is strictly $0. Relying on pgcrypto for BVNs or card tokens in high-throughput production environments degrades PostgreSQL connection scaling and risks exposing master encryption keys in database query logs.

Frequently Asked Questions

Should we hash or encrypt BVNs in our PostgreSQL database?

If you only need to match a user-provided BVN against a previously recorded value for duplication checks, store a salted hash (e.g., HMAC-SHA256 with a secure secret). However, fintech engines usually need to transmit the unencrypted 11-digit BVN to NIBSS, Paystack, or identity verification providers during onboarding. In this case, you must encrypt, not hash, because hashing is one-way and irreversible.

How does key rotation work under NDPR without taking our platform offline?

HashiCorp Vault Transit Engine solves this by tagging ciphertexts with key version prefixes (e.g., vault:v1:abc...). When you rotate the master key to v2, Vault continues decrypting v1 records without error. You can run an asynchronous background worker that reads records, calls Vault's /transit/rewrap endpoint to update the ciphertext to v2, and updates Postgres without ever exposing the unencrypted BVN in application memory.

Is encrypting PII at the database volume level (AWS EBS Encryption / Hetzner LUKS) sufficient for NDPR compliance?

No. Storage-level encryption (encryption at rest at the block device level) only protects data if physical hard drives are stolen from a data center. It does not protect against SQL injection vulnerabilities, leaked DB connection strings, compromised database backups, or unauthorized developer query access. NDPR auditors explicitly look for application-layer or column-level encryption for sensitive personal identification numbers.

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#Fintech#AWS KMS#HashiCorp Vault#PostgreSQL#Encryption

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.