Security

NDPR PII Encryption: HashiCorp Vault Transit vs AWS KMS Envelope vs Postgres pgcrypto

C
Chidi OkekeVP of Frontend Engineering
October 26, 202615 min read
NDPR PII Encryption: HashiCorp Vault Transit vs AWS KMS Envelope vs Postgres pgcrypto

Storing raw BVN, NIN, and bank account numbers in plain text will trigger massive regulatory penalties under NDPA 2023. We benchmark HashiCorp Vault Transit, AWS KMS envelope encryption, and Postgres pgcrypto across latency, cost, and audit rigor.

Storing plain-text Bank Verification Numbers (BVNs), National Identification Numbers (NINs), or phone numbers in a production database is a multi-million Naira risk. Under the Nigeria Data Protection Act (NDPA 2023), enforced by the Nigeria Data Protection Commission (NDPC), failing to protect Personally Identifiable Information (PII) at rest can land your company with penalties up to 2% of annual gross revenue or ₦10,000,000—whichever is higher.

Beyond legal compliance, database dumps leaked through compromised staging environments, rogue database administrator (DBA) access, or unredacted SQL query logging remain the primary vector for data breaches in Nigerian fintech.

To pass an NDPC audit and protect customer data, application architecture must decouple data storage from data decryption keys. This requires a deterministic strategy: searchable PII must be blinded using an HMAC-SHA256 with a secret pepper, while raw values needed for downstream API calls (such as sending BVNs to NIBSS or identity verification vendors) must be encrypted using field-level encryption before reaching the database storage layer.

In this comparison, we evaluate three primary architectures used by engineering teams in Lagos to implement field-level encryption for PII: HashiCorp Vault Transit Secret Engine, AWS KMS Client-Side Envelope Encryption, and Postgres pgcrypto.


HashiCorp Vault Transit: Centralized Encryption-as-a-Service

HashiCorp Vault’s Transit secret engine treats encryption and decryption as an API call. Your application sends plaintext PII to Vault, and Vault returns a ciphertext string structured like vault:v1:8gfD3kL.... The key never leaves Vault’s memory, and the database engine never sees the plaintext or the root encryption keys.

Architectural Advantages

  • Zero Key Exposure: Neither application developers nor DBAs ever handle the master encryption keys. Keys are generated, rotated, and protected inside Vault.
  • Built-in Key Rotation: Rotating a key requires an API call to Vault. Old data remains decryptable using older key versions (e.g., vault:v1: vs vault:v2:), and re-wrapping data with a new key version can be done lazily in background jobs without decrypting PII back to plaintext on application servers.
  • Infrastructure Agnostic: Vault runs identically whether hosted on AWS, GCP, or bare-metal servers. If you are replacing AWS EKS with Nomad and WireGuard on Hetzner, Vault fits seamlessly into your private network without cloud provider lock-in.

Practical Drawbacks

  • Network Latency Overhead: Every read or write operation involving encrypted fields incurs a network round-trip from your application service to the Vault cluster. If your API endpoint hydrates a list of 50 users and decrypts their phone numbers sequentially over an HTTP API, latency will spiral to hundreds of milliseconds.
  • Operational Complexity: Running high-availability (HA) self-hosted Vault requires setting up Integrated Storage (Raft), unseal keys (or AWS KMS auto-unseal), TLS mutual authentication, and automated backup routines. If Vault goes down, your entire backend loses the ability to process transactions.

AWS KMS Client-Side Envelope Encryption: Scalable Cloud Key Management

AWS Key Management Service (KMS) envelope encryption avoids making network requests for every field decryption. Instead of sending the payload to AWS for every operation, your application requests a Data Encryption Key (DEK) from AWS KMS using a Master Key (KMS Key ARN).

AWS KMS returns a plaintext DEK and an encrypted DEK. The application uses the plaintext DEK locally in memory (e.g., using AES-GCM) to encrypt the user's BVN, attaches the encrypted DEK alongside the encrypted payload in PostgreSQL, and immediately zeroizes (wipes) the plaintext DEK from application memory.

Architectural Advantages

  • Performance at Scale: By utilizing the official AWS Encryption SDK with Data Key Caching, application instances cache plaintext DEKs in memory for a short window (e.g., 5 minutes or 1,000 executions). This reduces network latency for encryption/decryption down to local CPU execution time (microseconds).
  • Granular IAM Policies: Access to decrypt data can be scoped to specific IAM roles attached to microservices. A customer onboarding worker service can be granted kms:GenerateDataKey and kms:Decrypt access, while an analytics reporting service is strictly denied KMS permissions.
  • Zero Server Management: AWS manages KMS availability, key durability, and Hardware Security Module (HSM) compliance (FIPS 140-3 Level 3).

Practical Drawbacks

  • Cloud Lock-in & FX Volatility: AWS KMS charges per key per month plus $0.03 per 10,000 requests. For high-volume transaction engines handling millions of reads/writes, un-cached KMS usage billed in USD can introduce volatile infrastructure costs for teams earning in NGN.
  • Strict AWS Dependency: Tying application-level encryption directly to AWS KMS API libraries makes multi-cloud deployments or localized deployments significantly more complex.

Postgres pgcrypto: The In-Database Shortcut

pgcrypto is a native PostgreSQL extension providing cryptographic functions such as pgp_sym_encrypt() and pgp_sym_decrypt(). Encryption and decryption occur inside PostgreSQL during the SQL query execution.

-- Symmetric encryption inside PostgreSQL
INSERT INTO users (id, bvn_encrypted) 
VALUES (1, pgp_sym_encrypt('22233344455', 'my-secret-passphrase'));

Architectural Advantages

  • Zero Extra Infrastructure: No separate Vault cluster or AWS KMS setup is required. Enable the extension via CREATE EXTENSION IF NOT EXISTS pgcrypto; inside PostgreSQL.
  • Familiar Query Flow: Encryption happens inside standard SQL INSERT and SELECT statements, making it simple for small teams to integrate into legacy applications quickly.

Practical Drawbacks

  • Exposed Secret Keys in Query Logs: Passing the decryption key inside SQL strings (pgp_sym_decrypt(bvn_encrypted, 'my-secret-passphrase')) means raw keys appear in plain text across PostgreSQL query logs, slow query monitors, connection pooler logs (e.g., PgBouncer), and application APM tracing systems.
  • PostgreSQL CPU Overhead: Performing heavy cryptographic operations (AES/PGP) directly inside PostgreSQL shifts computational overhead to your database instance. While scaling backend API servers horizontally is cheap, scaling a primary PostgreSQL instance vertically to handle CPU-bound crypto operations is extremely expensive.
  • Poor NDPC Audit Defense: Because the secret key must be supplied by the application connecting to PostgreSQL, anyone with database access who captures the connection string or inspects server processes can decrypt the entire database.

Head-to-Head Comparison

| Criteria | HashiCorp Vault Transit | AWS KMS Envelope Encryption | Postgres pgcrypto | | :--- | :--- | :--- | :--- | | P99 Latency Overhead | Medium (2–10ms per API batch call) | Very Low (< 0.5ms with DEK caching) | Low-Medium (Consumes DB host CPU) | | Operational Overhead | High (Self-hosted) / Low (HCP Vault) | Zero (Fully Managed AWS) | Low (Database Extension) | | NDPC/NDPA Audit Rigor| Excellent (Strict Separation of Duties) | Excellent (FIPS 140-3 HSM + CloudTrail) | Poor (Key leak risk in query logs) | | Key Rotation Effort | Low (Automatic versioning via API) | Low (AWS Automated annual key rotation) | High (Requires manual table re-encryption) | | Infrastructure Cost | Predictable (Compute instance cost) | Variable ($0.03 per 10,000 KMS requests) | Low (Uses existing DB resources) | | Vendor Lock-in | None (Open Source / Agnostic) | High (AWS IAM & KMS APIs) | None (Standard Postgres) |


Implementation Walkthrough: Vault Transit vs AWS KMS in Go

Below is a production-ready comparison in Go demonstrating how an application service encrypts a sensitive BVN string before persistence.

Option A: Vault Transit API Pattern

Using the official HashiCorp Vault API Client:

package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"log"

	vault "github.com/hashicorp/vault/api"
)

type VaultEncryptor struct {
	client  *vault.Client
	keyName string
}

func (v *VaultEncryptor) EncryptBVN(ctx context.Context, rawBVN string) (string, error) {
	// Base64 encode the payload as required by Vault Transit API
	encodedPayload := base64.StdEncoding.EncodeToString([]byte(rawBVN))

	data := map[string]interface{}{
		"plaintext": encodedPayload,
	}

	// Call Vault Transit Encrypt Endpoint
	secret, err := v.client.Logical().WriteWithContext(ctx, fmt.Sprintf("transit/encrypt/%s", v.keyName), data)
	if err != nil {
		return "", fmt.Errorf("vault encrypt call failed: %w", err)
	}

	ciphertext, ok := secret.Data["ciphertext"].(string)
	if !ok {
		return "", fmt.Errorf("invalid cipher text returned from vault")
	}

	return ciphertext, nil
}

Option B: AWS KMS Envelope Encryption Pattern

To prevent hitting AWS KMS rate limits and incurring excess billing costs during high throughput operations, use local AES-GCM envelope encryption alongside KMS key generation:

package main

import (
	"context"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"fmt"
	"io"

	"github.com/aws/aws-sdk-go-v2/service/kms"
	"github.com/aws/aws-sdk-go-v2/service/kms/types"
)

type KMSEnveloper struct {
	kmsClient *kms.Client
	kmsKeyArn string
}

// EncryptPII generates a local Data Key from KMS and encrypts the BVN using AES-GCM
func (k *KMSEnveloper) EncryptPII(ctx context.Context, plaintext string) ([]byte, []byte, error) {
	// 1. Request Data Encryption Key (DEK) from AWS KMS
	keyOutput, err := k.kmsClient.GenerateDataKey(ctx, &kms.GenerateDataKeyInput{
		KeyId:         &k.kmsKeyArn,
		KeySpec:       types.DataKeySpecAes256,
	})
	if err != nil {
		return nil, nil, fmt.Errorf("kms generate data key failed: %w", err)
	}

	// 2. Create local AES cipher using the returned plaintext DEK
	block, err := aes.NewCipher(keyOutput.Plaintext)
	if err != nil {
		return nil, nil, err
	}

	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, nil, err
	}

	nonce := make([]byte, gcm.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, nil, err
	}

	// 3. Encrypt data locally using AES-GCM
	ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)

	// Return both the encrypted payload AND the encrypted DEK.
	// The encrypted DEK is stored in DB alongside the payload.
	return ciphertext, keyOutput.CiphertextBlob, nil
}

In high-volume engines where you hit database constraints during scaling, pairing AWS KMS envelope encryption with local key caching guarantees low latency without overwhelming database CPU limits—similar to structural decisions faced when evaluating Redis Mutexes vs Postgres Advisory Locks for Paystack Webhook Idempotency.


Recommendation Matrix: Which One Should You Build?

Go with AWS KMS Envelope Encryption if:

  1. Your infrastructure is hosted entirely within AWS (ECS, EKS, or EC2).
  2. Low P99 response time is critical for your payment flows.
  3. You want zero operational headache managing encryption clusters, and your team relies on AWS IAM for service permission boundaries.

Go with HashiCorp Vault Transit if:

  1. You operate a multi-cloud or hybrid infrastructure (e.g., core workloads on Hetzner to save infrastructure costs, with fallback instances elsewhere).
  2. You require strict separation of operational duties where developers and cloud admins cannot view raw encryption keys or access cloud vendor key logs.
  3. You require centralized secrets management beyond field-level encryption (e.g., dynamic database credentials, PKI certificate generation).

Avoid Postgres pgcrypto for PII except if:

  1. You are building an early-stage internal prototype or staging tool where NDPA regulatory compliance is not yet enforced.
  2. You have zero external network dependencies and cannot run a secondary Vault sidecar container. Note: If used in production, you must ensure PostgreSQL statement logging is strictly configured to obscure query parameters (log_statement = 'none'), which degrades outage troubleshooting capabilities.

Frequently Asked Questions

Is hashing a BVN with SHA-256 sufficient for NDPR compliance?

No. One-way hashing (SHA-256) is non-reversible. While salted hashing or HMAC-SHA256 is required for searching or deduplicating records (e.g., checking if a BVN already exists in your platform), you must use reversible field-level encryption (such as AES-256-GCM) whenever your application needs to retrieve the raw BVN to communicate with NIBSS, CBN, or identity verification APIs.

What is the difference between encryption at rest (AWS EBS/RDS) and field-level encryption?

Disk-level encryption (like AWS RDS KMS storage encryption) protects data against physical drive theft at the data center level. However, if an attacker gains access to your database via SQL injection, stolen database credentials, or an unredacted log file, disk-level encryption does not protect you because the database engine transparently decrypts the data for any connected user. Field-level encryption ensures that raw PII values remain encrypted inside database columns even if the entire database dump is leaked.

How does key rotation work with HashiCorp Vault Transit without causing downtime?

Vault uses key versioning. When you rotate a key, Vault increments the key version (e.g., from v1 to v2). New write operations automatically use v2. When reading existing data encrypted with v1, Vault inspects the vault:v1: prefix on the ciphertext and uses key version v1 to decrypt it. You can re-encrypt historical data in the background using Vault’s rewrap endpoint without exposing plaintext data to your application servers.

Does storing encrypted PII break database searching and indexing?

Yes. Randomized encryption algorithms like AES-GCM output different ciphertexts for the exact same input string every time. To search for a user by BVN or phone number without decrypting the entire database table, store a deterministic HMAC-SHA256 hash (using a secret server-side pepper) in a separate index column (bvn_lookup_hash). Query against bvn_lookup_hash for exact matches, and decrypt bvn_encrypted only when raw display is necessary.

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

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.