Digital Systems7 min read

Ecommerce data encryption: envelope encryption, KMS and key rotation

A practical method for classifying data, implementing envelope encryption, governing KMS keys and rotating them without losing decryptability.

Layered transparent capsules surrounded by protective rings and metallic discs in a digital infrastructure

Protect data where the application uses it

An ecommerce platform retains addresses, order references, support notes and operational attributes beyond a single request. Disk and backup encryption are important controls, but they do not replace application-level protection for selected fields: when the database is mounted, the underlying storage is available too. The aim is to reduce what an unauthorised copy of the datastore can reveal while keeping data readable only by authorised services at authorised times.

Start with an inventory. For every field, record purpose, owner, readers, retention, search and deletion. Remove what is unnecessary and assign consistent classes. This article concerns persistent application data, not TLS, passwords, card numbers, tokenisation or general secret management, which require different controls.

Define the threat model and trust boundary

Describe the events you intend to contain: an unauthorised database copy, an exposed backup, excessive operator privilege or a compromised service. Decide which components may request decryption and which should see ciphertext only. Encryption cannot repair broken application authorisation or fully protect against a process compromised while it already has permission to decrypt. Pair it with identity, least privilege, auditing and data minimisation.

Separate data, data keys and wrapping keys

With envelope encryption, the application encrypts a payload using a data encryption key, or DEK, generally generated for one object or a tightly bounded set. The plaintext DEK is then encrypted by a key encryption key, or KEK, protected by KMS. The stored record contains the payload ciphertext, encrypted DEK and metadata needed to interpret the format. The KEK stays inside the KMS boundary, while the plaintext DEK exists only for the necessary operation.

This structure avoids sending large payloads to KMS and centralises governance of wrapping keys. Do not invent primitives or formats. Use a maintained cryptographic library that provides authenticated encryption, sound random generation and a versioned message format. Authenticated encryption lets the application detect modification of ciphertext and associated authenticated data before it releases plaintext.

Design a versioned envelope

Define an explicit schema containing a format version, logical key reference, library-managed algorithm or suite, encrypted DEK, required nonce or parameters, ciphertext and authentication tag when separate. Never persist the plaintext DEK. Store the key reference plus format or provider metadata sufficient to interpret each envelope. Some AWS and Google ciphertext formats already carry information needed for decryption, so do not require a separate key-material version field universally.

Bind ciphertext to ecommerce context

When supported by the library and KMS, use authenticated encryption context to bind an envelope to its record type, tenant and purpose. Technically it is arbitrary associated data, but it is not secret: it can remain in plaintext and may appear in key-service logs. It therefore should not contain sensitive or personal data. Keep its keys and values stable, and test that moving an envelope to another tenant or record causes a controlled failure.

Persist opaque technical identifiers and a policy version, not sensitive business details. The caller must reconstruct the same context deterministically. If a migration changes identifiers, introduce a compatibility stage or re-encrypt before the change. Production is the wrong place to discover that new code cannot reproduce parameters used by existing envelopes.

Minimise KMS permissions and separate duties

A write path may be allowed to generate or encrypt a DEK without gaining administrative rights over the KEK. A read path should decrypt only envelopes allowed by its context. Rotation, disablement, policy changes and deletion scheduling belong to separate operational roles. Avoid wildcard access and prove conditions with negative tests: an unapproved service, environment or tenant must receive a controlled denial.

Treat KMS audit events as sensitive signals. Capture operation, workload identity, key, result, environment and application correlation without copying plaintext or DEKs. Alert on unexpected decryption volume, new identities, permission failures and use of keys approaching retirement. Useful auditing connects a key request to an ecommerce flow without turning logs into another store of personal information.

Design rotation before the first record is written

Separate three operations. Automatic or on-demand rotation of key material can preserve a key’s logical identity while historical material remains available to decrypt existing ciphertext. Creating and adopting another KMS key changes key identity. Neither operation automatically re-encrypts stored envelopes; Google Cloud states explicitly that rotation does not re-encrypt existing ciphertext. Re-encrypting a wrapped DEK with an operation such as ReEncrypt, without exposing plaintext key material to the caller, is a separate migration with its own permissions and rollout.

Set cryptoperiods from risk, volume, incident capability and internal obligations. Keep every referenced key or retained historical material usable while an envelope depends on it; premature deletion makes data irrecoverable. Before each stage, count references and verify backups, replicas and queues.

Choose gradual rotation, migration or both

A lazy strategy re-encrypts an envelope when its record is read or updated. It reduces peak work but extends coexistence between versions. A batch migration shortens that window but needs rate limits, checkpoints, idempotency and KMS cost controls. A hybrid is often practical: new data uses the current key, active records move in batches and rare objects enter a residual queue. Every path must be safely pausable without ambiguous records.

Handle caching, failures and outages without shortcuts

A plaintext DEK cache can reduce latency and KMS calls, but expands the time and memory where key material is exposed. If the library supports caching, bound lifetime, uses and scope; never turn it into permanent storage. Clear buffers where the environment permits and never log them. Measure hits, expiry and decrypt operations, then compare the benefit with the risk of the specific workflow.

If KMS is unavailable, never degrade to stored plaintext or skip authentication checks. Classify errors as transient, authorisation, format or integrity failures. Apply bounded retries only where safe, queue deferrable work and return an explicit error when a read cannot be served. The runbook should distinguish an outage, a broken policy, a disabled key, a corrupted envelope and mismatched context.

Migrate and release without a dangerous rewrite

Add compatible envelope fields, then enable dual reading: prefer encrypted format and use the legacy value only during a controlled migration. Turn on encrypted writes, backfill in small batches and verify each result by decrypting it in an authorised process. Once coverage is proven, remove the fallback and delete the old field under the retention policy. Avoid indefinite dual writing because it creates two sources of truth.

Prepare rollbacks for code and policy that do not require losing keys. A canary subset should cover encryption, decryption, wrong context, an old key, retries and restore from backup. Keep permanent synthetic fixtures for operational exercises; do not use customer data in those tests. Final verification must include exports, asynchronous jobs and authorised support tools, not only the storefront request.

Measure security, reliability and progress

Build a baseline with the share of records on the current format, envelopes by KEK reference or equivalent provider metadata, errors by class, encrypt and decrypt latency, KMS calls, cache hits, migration backlog and observed cost. Include the time needed to revoke an identity and complete a rotation exercise. There is no universal threshold: derive objectives from actual traffic and risk, then prove alerts with controlled events.

Review the inventory, permissions, formats and cryptographic dependencies regularly. The design remains useful only when the team can rotate, recover and investigate without exposing plaintext. To integrate application encryption with architecture, observability and release processes, explore our digital systems and ecommerce services. The target is a verifiable chain: minimal data, versioned envelopes, governed keys and rehearsed procedures.

crittografia applicativadati ecommerceenvelope encryptionkey managementkmsrotazione chiavisicurezza dati

Frequently asked questions

What is the difference between a DEK and KEK in envelope encryption?

The DEK encrypts application data; the KMS-protected KEK encrypts that DEK. Storage receives ciphertext, the encrypted DEK and metadata, never the plaintext DEK.

Does rotating a KMS key require re-encrypting every payload?

Not always. Automatic or on-demand material rotation can preserve key identity and historical material; adopting another key changes identity. Re-encrypting wrapped DEKs is a separate migration.

Can encryption context contain personal data?

Technically, context is arbitrary associated data, but it is not secret and may appear in plaintext or KMS audit events. It therefore should not contain sensitive or personal data.

How should an ecommerce service handle a temporary KMS outage?

It must not persist plaintext. Classify the failure, bound safe retries, queue deferrable work and use a runbook to distinguish outages, policies, disabled keys and damaged envelopes.

Related articles

Got a similar project?

Tell us the problem. We'll build the solution.

Let's talk

Have a project in mind?

Tell us the problem. We'll build the solution.

Let's talk