ARTICLE

Magento 2 Encryption Key Rotation: encryption:key:change, Re-Encrypting Stored Secrets, and Recovering From CosmicSting

Magento 2 Encryption Key Rotation: encryption:key:change, Re-Encrypting Stored Secrets, and Recovering From CosmicSting

Rotating the Magento 2 encryption key means running bin/magento encryption:key:change, which appends a new key to crypt/key in app/etc/env.php. That alone is not enough. Existing secrets stay encrypted with the old key until you re-encrypt them, and the old key keeps working until you retire it. A full rotation is change, re-encrypt, verify, retire.

Most guides stop after the first command. That leaves a store in the state that made the CosmicSting attacks so damaging: a patched site whose stolen key is still accepted. This guide covers what the key protects, what each Adobe command does and does not do, the gaps you have to close yourself, and the order to do it in.

What the encryption key is and where it lives

Adobe’s encryption key documentation says the key protects passwords and other sensitive data, including credit card data and the credentials for payment and shipping integrations, using ChaCha20-Poly1305 with a 256 bit key.

The key is stored under crypt/key in app/etc/env.php. After a rotation that value holds more than one key, one per line:

'crypt' => [
    'key' => 'oldkeyoldkeyoldkeyoldkeyoldkey00
base64NEWKEYNEWKEYNEWKEYNEWKEYNEWKEYNEWKEYNEW='
],

Each encrypted value in the database records which line it was encrypted with. A stored value looks like 1:3:Zm9v..., where the first number is the key’s position in that list (starting at 0) and the second is the cipher version. Two consequences follow:

  • Never delete an old key line. The positions would shift and every value would point at the wrong key. To take a key out of service you replace its content, you do not remove the line.
  • New writes use the last key. Anything saved after rotation is encrypted with the newest line. Anything saved before still needs the old one to be readable.

The same key is also used outside encryption. It signs the JSON Web Tokens Magento issues for the web API, and it feeds hashes, including the hash in product image cache paths.

What encryption:key:change actually does

Since Magento 2.4.8 the CLI is the only supported way. Adobe states that the key change feature in the admin (System > Other Settings > Manage Encryption Key) is deprecated and was removed in 2.4.8.

bin/magento list | grep encryption:key:change
bin/magento maintenance:enable
# stop cron: crontab -e on premises, ece-tools cron:disable on Cloud
bin/magento encryption:key:change
bin/magento cache:flush
# start cron again
bin/magento maintenance:disable

Adobe’s procedure wraps the command in maintenance mode with cron stopped, so nothing writes encrypted values halfway through. Our guide to Magento 2 maintenance mode covers the allowlist you will want so your own team can test before reopening. app/etc/env.php must be writable for the command to succeed.

Two things to expect, both documented by Adobe:

  • Rotating the key immediately invalidates all customer and admin sessions, excluding integration users. Everyone logs in again.
  • You should record the new key somewhere secure. Without it, encrypted data cannot be recovered if the file is lost.

On patch levels older than the ones that ship the command, Adobe published isolated patches (the ac-12589 composer patch archives) that add it. If bin/magento list does not show the command, apply the patch for your version line first. Our article on the Magento Quality Patches Tool explains how to apply and track patches like that with Composer.

What gets re-encrypted, and what does not

Adobe’s developer guide on data re-encryption describes two built in re-encryptors:

bin/magento encryption:data:list-re-encryptors
bin/magento encryption:data:re-encrypt core_config_data sales_order_payment
Data Covered by core re-encryption What to do
Encrypted system configuration in core_config_data Yes, for fields using the standard encrypted backend model Run the core_config_data re-encryptor
Saved card data in sales_order_payment Yes Run the sales_order_payment re-encryptor
Config values encrypted by third party modules in nonstandard ways Not reliably Find them and re-encrypt, or re-save them in the admin
OAuth and integration tokens and secrets No Re-encrypt the columns, or reissue the integration
Admin two-factor authentication secrets No Re-encrypt, or have admins re-enroll
Custom tables in your own or vendor extensions No Register a custom re-encryptor
Encrypted values held in env.php or cloud variables No Re-encrypt and update them by hand
Credentials issued by an outside provider Not applicable Reissue at the provider if the key was stolen

The “No” rows come from the people who had to deal with this in production. The open source encryption key manager module from Gene Commerce, published on GitHub, exists because core leaves those values on the old key, and its README lists the columns it had to handle separately, including admin user, customer, OAuth token, and two-factor tables.

For your own tables, Adobe’s guide shows the supported extension point: declare a virtual type of Magento\EncryptionKey\Model\Data\ReEncryptorList\ReEncryptor\SimpleHandler with the table name, identifier field, and columns, wrap it in a ReEncryptor virtual type with a description, and add it to the reEncryptors argument of Magento\EncryptionKey\Model\Data\ReEncryptorList in di.xml. It then appears in list-re-encryptors and can be run by name.

Side effects outside the database

  • Product image cache. The cache path hash depends on the key, so a new key means Magento regenerates resized images. On a large catalog, plan for that load. Our article on the Magento 2 product image cache explains how to pre-warm it. The Gene module includes a hasher that keeps the old hash to avoid this.
  • Anything your code hashes with the key. Search custom modules for calls to the encryptor’s hash() method. Stored hashes will stop matching.
  • Every environment. Staging and developer copies that share the production key need the new one too, or encrypted config imported from production will not decrypt.

Retiring the old key

This is the step that matters after a compromise, and the one the core command does not do. As long as the old key is present in crypt/key, it can still decrypt, and on unpatched logic it can still validate tokens.

The safe sequence is:

  1. Re-encrypt everything you can find.
  2. Verify that nothing readable still depends on an older key.
  3. Replace the old key’s line with placeholder text of the same position. Do not delete the line.

Tooling makes this far less error prone than doing it by hand. Bemeir maintains an open source script for exactly this, magento2-rotate-encryption-keys on GitHub, released under the MIT license. Its README describes commands to scan every text and binary column for encrypted values, including ones nested inside JSON and serialized data, re-encrypt them as a dry run by default, verify that nothing still depends on an older key, and only then retire old key lines with placeholders. It is provided as is, without warranty, and the README is clear about its limits: it cannot rotate data protected by an extension’s own cryptography, and it does not reissue credentials at their source. Rehearse on a copy of the database and take a backup before any write.

Recovering from CosmicSting

CosmicSting is the name Sansec gave to CVE-2024-34102. Sansec’s CosmicSting research calls it the worst bug to hit Magento and Adobe Commerce stores in two years, with a CVSS score of 9.8. The attack reads app/etc/env.php, which gives the attacker the encryption key. With the key they forge a JSON Web Token with full API access, then use the REST API to append skimmer scripts to CMS blocks.

The timeline in Sansec’s write-up explains why so many stores were caught: Adobe released the fix on June 11, 2024, Sansec reported 75 percent of stores still unpatched a week later, and the first attacks in the wild appeared on June 23. Later campaigns breached more than 2,000 stores in a few hours in October and nearly 3,000 in a second wave in November.

The key point from Sansec is that patching is not recovery. A key stolen before the patch still works afterward, and generating a new key does not invalidate the old one. Sansec’s guidance is to assume the key was stolen on any store that was not upgraded before June 25, 2024.

A complete recovery, in order:

  1. Patch or upgrade so the key cannot be read again. Rotating first is pointless if the hole is still open.
  2. Rotate the key with encryption:key:change.
  3. Re-encrypt with the core re-encryptors, then handle the gaps in the table above.
  4. Retire the old key so tokens signed with it are rejected.
  5. Remove what the attacker may have added. Sansec notes that existing API tokens are stored in the database and are not derived from the key, so they survive rotation. Review integrations and delete any you do not recognize. Reset admin passwords and review admin users. Our guide to securing Magento admin access with 2FA, SSO, and role permissions covers hardening that side.
  6. Inspect content. Check CMS blocks and pages for injected script tags, and compare against a known good backup.
  7. Reissue outside credentials. Payment gateway keys, shipping account passwords, and API secrets that were stored encrypted should be treated as exposed and regenerated at the provider.
  8. Test checkout and payment, every integration, transactional email, and admin and customer login.

Rotation on Adobe Commerce Cloud

On Cloud the key usually arrives through an environment variable. Adobe’s troubleshooting article for CVE-2024-34102 recommends that route: read the current value from CRYPT_KEY or crypt/key, generate a new key (for 2.4.7, openssl rand -base64 32 with the output prefixed by base64; for 2.4.6 and earlier, openssl rand -hex 16), append it to the existing value on a new line, and set the combined value as env:MAGENTO_DC_CRYPT__KEY. Saving the variable triggers a redeploy. If you mark the variable as sensitive it is hidden from every interface afterward, so keep your own secure copy.

How often should you rotate?

Adobe’s documentation says the key should be changed regularly and whenever the original might be compromised. In practice the triggers are concrete: a known vulnerability that exposes local files, a developer or agency with env.php access leaving, a leaked backup or repository, or a compliance schedule. A rotation you have rehearsed on staging is a small maintenance window. One attempted for the first time during an incident is not.

Does the storefront theme matter?

No. The key and everything encrypted with it are backend concerns, and the process is identical on Luma and Hyva. The only frontend visible effects are logged out customers and regenerated product images. For stores on our Hyva development services, the post rotation test plan is the same checkout, login, and integration pass as any other release.

Platform context

Key management is one of the responsibilities you take on with a self hosted platform. On hosted platforms such as Shopify and BigCommerce, the vendor manages application secrets and merchants rotate API credentials for their apps. Shopware, like Magento, can be self hosted and carries its own secret handling duties. None of that makes one model better. It does mean a Magento team needs a written rotation runbook.

Where Bemeir fits

Bemeir is a Brooklyn agency that builds, upgrades, and supports Magento and Adobe Commerce stores. Security patching and key rotation are part of the support work in our Magento development services. You can read more about Bemeir or see our technology partners.

FAQ

Does encryption:key:change re-encrypt existing data?

No. It appends a new key to crypt/key in app/etc/env.php. Existing values stay encrypted with the old key until you run encryption:data:re-encrypt for system configuration and payment data, and handle other tables separately.

Can I delete the old encryption key after rotating?

Do not delete the line. Encrypted values store the position of the key that encrypted them, so removing a line shifts every position. After re-encrypting and verifying, replace the old key’s content with a placeholder so the line count stays the same.

Where is the Magento 2 encryption key stored?

In app/etc/env.php under crypt/key, or in an environment variable on Adobe Commerce Cloud. After a rotation the value contains several keys, one per line, and the last one is used for new writes.

Is upgrading enough to recover from CosmicSting?

No. Upgrading stops the key from being read again, but a key that was already stolen still works. Sansec advises rotating the key, invalidating the old one, deleting unknown API integrations, and resetting admin passwords.

Will rotating the key log customers out?

Yes. Adobe states that rotation immediately invalidates all customer and admin sessions, excluding integration users. Schedule it for a quiet period and tell your support team.

Let us help you get started on a project with Magento 2 Encryption Key Rotation: encryption:key:change, Re-Encrypting Stored Secrets, and Recovering From CosmicSting and leverage our partnership to your fullest advantage. Fill out the contact form below to get started.

more articles about ecommerce

Read on the latest with Shopify, Magento, eCommerce topics and more.