Sharcon AI Automation CompanySHARCON
Back to Blog
n8n
security
credentials
workflow-automation
devops

n8n Credentials Encryption and Key Security

October 8, 2026

Learn how n8n encrypts credentials at rest using AES, manage N8N_ENCRYPTION_KEY, fix mismatch errors, and configure secure key rotation.

n8n encrypts all stored API keys, OAuth tokens, and database passwords at rest using AES encryption derived from a master encryption key. This encryption key is set via the N8N_ENCRYPTION_KEY environment variable or generated automatically in your configuration folder upon first startup. Managing this encryption key correctly is mandatory to prevent permanent credential loss, mismatch errors, and unauthorized access to your workflow secrets.

How n8n Encrypts Credentials at Rest

When you save credentials in n8n, the application does not store plain text API keys or passwords in its database. Instead, n8n serializes the credential object, encrypts the payload using AES encryption, and stores the encrypted blob in the credentials_entity table (in SQLite, PostgreSQL, or MySQL).

The encryption process relies on a single symmetric key. By default:

  1. Self-Hosted / Docker Installations: If N8N_ENCRYPTION_KEY is not set, n8n generates a random key during its initial startup and writes it to ~/.n8n/config (or /home/node/.n8n/config inside official Docker containers).
  2. Environment Variable Override: If N8N_ENCRYPTION_KEY is defined in your environment file or container configuration, n8n uses that exact key for all cryptographic operations, ignoring any local config file.
+------------------+      +-----------------------+      +-------------------------+
| Plain Credential | ---> |    AES Encryption     | ---> | DB: credentials_entity  |
| (API Key / Pass) |      | (N8N_ENCRYPTION_KEY)  |      | (Encrypted Blob)        |
+------------------+      +-----------------------+      +-------------------------+

If n8n attempts to read a database containing credentials that were encrypted with a different key, decryption fails immediately with a mismatch error.


Generating and Setting a Production Encryption Key

Relying on auto-generated configuration files inside Docker containers is risky because destroying the container volume without backing up ~/.n8n/config renders your credentials unreadable.

If no key is set, n8n generates a random one and stores it in ~/.n8n/config; for production generate your own with openssl rand -hex 32 (64 hex characters).

Step 1: Generate a Cryptographically Secure Key

Run the following command in your terminal to generate a 64-character hexadecimal key:

openssl rand -hex 32

Example output: a3f89e21b4c90d8e7f123456789abcdef0123456789abcdef0123456789abcde

Step 2: Configure Environment Variables

Add the generated key to your production environment configuration.

Docker Compose (docker-compose.yml):

version: '3.8'

services:
  n8n:
    image: n8nio/n8n:latest
    restart: always
    environment:
      - N8N_ENCRYPTION_KEY=a3f89e21b4c90d8e7f123456789abcdef0123456789abcdef0123456789abcde
      - N8N_HOST=automation.yourdomain.com
      - N8N_PORT=5678
      - DB_TYPE=postgresdb
      - DB_POSTGRESDB_HOST=postgres
      - DB_POSTGRESDB_DATABASE=n8n
      - DB_POSTGRESDB_USER=n8n_user
      - DB_POSTGRESDB_PASSWORD=secure_db_password
    volumes:
      - n8n_data:/home/node/.n8n

volumes:
  n8n_data:

For custom integrations connecting external services to custom infrastructure, review our backend and API development services.


Fixing the "Mismatching Encryption Keys" Error

The Mismatching encryption keys error occurs when n8n boots up, connects to a database containing previously saved credentials, but reads an N8N_ENCRYPTION_KEY that does not match the key used during initial creation.

Common Causes

  1. Recreated Docker Containers: You recreated an n8n Docker container without mounting a persistent volume for /home/node/.n8n, causing n8n to generate a new key on boot while the database retains old credentials.
  2. Database Migration: You pointed a new n8n instance at an existing PostgreSQL database without supplying the original N8N_ENCRYPTION_KEY.
  3. Queue Mode Mismatch: Main instances and worker processes in multi-instance setups use different environment files.

Resolution Steps

If you have the original key or config file:

  1. Stop the n8n service: docker compose down.
  2. Locate the original key from your backup or previous .env file.
  3. Update N8N_ENCRYPTION_KEY in your environment file.
  4. Restart n8n: docker compose up -d.

If the original encryption key is lost permanently, the encrypted data inside credentials_entity cannot be recovered. You must re-enter your credentials manually.


Queue Mode and Multi-Instance Cluster Security

When running n8n in scaled Queue Mode (with main processes, webhooks, and worker instances communicating via Redis), every single instance must share the exact same N8N_ENCRYPTION_KEY.

                  +---------------------------+
                  | Main Instance (UI/Editor) |
                  |  N8N_ENCRYPTION_KEY=KeyA  |
                  +-------------+-------------+
                                |
                                v
+---------------------------------------------------------------+
|                      Redis Queue & PostgreSQL                 |
+-------------------------------+-------------------------------+
                                |
      +-------------------------+-------------------------+
      |                                                   |
      v                                                   v
+---------------------------+       +---------------------------+
| Worker 1                  |       | Worker 2                  |
| N8N_ENCRYPTION_KEY=KeyA   |       | N8N_ENCRYPTION_KEY=KeyA   |
+---------------------------+       +---------------------------+

If a worker process has a missing or mismatched key, workflows that execute on that worker will throw Failed to decrypt credential errors at runtime.

Ensure your orchestration templates (Kubernetes ConfigMaps/Secrets, Docker Swarm, or AWS ECS task definitions) inject N8N_ENCRYPTION_KEY globally into all container definitions.

For scalable event-driven architectures and distributed workflow design, explore our business automation services.


CLI Export and Import Procedures: Plaintext vs Encrypted

n8n includes a Command Line Interface (CLI) for backing up and migrating workflows and credentials across environments.

Exporting Credentials

By default, exporting credentials via CLI outputs encrypted data blobs.

Exporting Encrypted Credentials:

docker exec -it n8n-container n8n export:credentials --all --output=/tmp/credentials.json

Encrypted credential exports are still sensitive — store them securely like secrets, separately from the key, rather than committing them to version control.

Exporting Decrypted Credentials (Sensitive):

docker exec -it n8n-container n8n export:credentials --all --decrypted --output=/tmp/credentials_plaintext.json

Warning: Adding --decrypted writes all API keys and secrets in plain text. Store this file exclusively in temporary in-memory storage or encrypted secret vaults. Never commit decrypted exports to Git repositories.

Importing Credentials

To import credentials into a target instance:

docker exec -it n8n-container n8n import:credentials --input=/tmp/credentials.json

If importing decrypted files:

docker exec -it n8n-container n8n import:credentials --input=/tmp/credentials_plaintext.json --decrypted

Environment Variables in Workflows and Access Control

n8n allows workflows to access system environment variables using the $env expression syntax (e.g., {{ $env.API_SECRET_KEY }}). While convenient, uncontrolled $env access creates security risks when multiple users build workflows on the same instance.

Restricting Environment Variable Access in Code Nodes

By default, JavaScript code executed inside the Code Node can read process environment variables via process.env.

To block Code Nodes from reading system environment variables, set:

N8N_BLOCK_ENV_ACCESS_IN_NODE=true

When enabled, JavaScript in Code Nodes cannot inspect process.env, preventing leakage of database credentials and system keys.

Using External Secrets Managers

For enterprise workloads, storing API keys inside individual workflows or local n8n storage can become unwieldy. Paid n8n plans support external secrets providers, including:

  • AWS Secrets Manager
  • HashiCorp Vault
  • Azure Key Vault
  • Google Cloud Secret Manager

With external secrets configured on paid plans, secrets are pulled from the vault at runtime instead of being stored in n8n.

To integrate custom enterprise software with secure workflow backends, see our integrations & software API services.


Safe Key Rotation Procedure

If an N8N_ENCRYPTION_KEY is compromised or security policy requires periodic key rotation, you must re-encrypt stored credentials with a new key. Simply changing N8N_ENCRYPTION_KEY in your environment file without migrating credentials will break access to existing secrets. Key rotation is not zero-downtime and requires a short maintenance window during which the n8n instance is stopped.

Rotation Execution Steps

  1. Export All Credentials Decrypted:
    n8n export:credentials --all --decrypted --output=/tmp/credentials_backup.json
    
  2. Export All Workflows:
    n8n export:workflow --all --output=/tmp/workflows_backup.json
    
  3. Stop n8n Service:
    docker compose down
    
  4. Update N8N_ENCRYPTION_KEY: Generate a new 64-character hex key with openssl rand -hex 32 and update N8N_ENCRYPTION_KEY in your .env file.
  5. Start n8n Service:
    docker compose up -d
    
  6. Re-import Decrypted Credentials:
    n8n import:credentials --input=/tmp/credentials_backup.json --decrypted
    
    n8n will re-encrypt every credential using the new N8N_ENCRYPTION_KEY.
  7. Securely Wipe Plaintext Backup File:
    shred -u /tmp/credentials_backup.json
    

(Note: Truncating database tables is a destructive step that should only ever be performed after verifying a complete, working backup.)


Credential Sharing and User Permissions

In multi-user n8n instances, credential ownership and sharing permissions dictate who can execute or modify workflows using specific API connections.

Role / FeatureDefault PermissionsSecurity Recommendation
Credential OwnerFull edit, delete, and share rightsRestrict owner role to lead automation engineers
Shared Read-OnlyCan use credential in workflows; cannot view secret valuesAssign to team members building standard flows
Global AdminCan manage all credentials and force ownership transferLimit to system administrators

Users with shared access to a credential can execute nodes using that credential, but n8n masks the underlying API keys in the user interface.


Backup Checklist for n8n Security

To ensure complete disaster recovery capability, store the following components in separate, secure locations:

  • N8N_ENCRYPTION_KEY: Saved in an offline password manager or cloud secret store.
  • Database Snapshots: Daily automated backups of PostgreSQL/MySQL n8n database.
  • Docker Volume Configuration: Persistent mounts for /home/node/.n8n.
  • Environment File Backup: Secure storage of .env files excluding plaintext keys.

Security Mistakes to Avoid

  1. Committing N8N_ENCRYPTION_KEY to Git: Hardcoding master keys in public or private repositories allows anyone with DB access to decrypt all stored secrets.
  2. Omitting Volume Persistence for /home/node/.n8n: Running unmounted Docker containers leads to automatic key regeneration upon container recreation.
  3. Leaving N8N_BLOCK_ENV_ACCESS_IN_NODE=false on Multi-User Instances: Allowing custom JavaScript nodes to read process.env exposes system credentials to non-admin workflow builders.
  4. Using Mismatched Encryption Keys Across Workers: In Queue Mode setups, mismatched keys cause intermittent workflow failures that are difficult to diagnose.
  5. Failing to Store Decrypted CLI Exports Securely: Leaving plaintext JSON credential dumps in temporary server directories creates high-risk exposure vectors.

Frequently Asked Questions

Does n8n store my API keys in plaintext anywhere?

No. n8n encrypts all credential fields at rest using AES encryption before saving them to the backend database. Credentials are only decrypted in memory during workflow execution.

What happens if I lose my N8N_ENCRYPTION_KEY?

If the encryption key is lost and no decrypted backup exists, the encrypted credentials in the database cannot be recovered. You will need to re-enter all API keys and OAuth connections manually.

How do I fix the "mismatching encryption keys" error in n8n?

Ensure your N8N_ENCRYPTION_KEY environment variable matches the key used when credentials were created. If running Docker, check that your volume mount for /home/node/.n8n is persistent.

Can worker instances in n8n Queue Mode use different encryption keys?

No. All main, webhook, and worker instances in an n8n cluster must use the exact same N8N_ENCRYPTION_KEY to decrypt credentials during workflow execution.

Is it safe to export n8n credentials with the CLI?

Encrypted credential exports still contain sensitive cryptographic data and should be stored securely like secrets, separately from the encryption key. Decrypted exports output plain text keys and must be stored in secure secret vaults.


Technical Support and Custom Implementation

If your team needs assistance architecting secure self-hosted n8n infrastructure, setting up high-availability Queue Mode clusters, or connecting custom enterprise CRMs, contact our automation team for expert technical support.

Max Lebedev

Max Lebedev

CEO of Sharcon LLC

15+ years in marketing and development. Leading a team of 30+ professionals at Sharcon.

Related Articles

Discover how AI agents in CRM boost South Florida businesses with automation, personalized support, and predictive insights for 2025.

speed to lead
lead follow-up automation
November 17, 2026

Speed to lead measures how quickly you respond to inquiries. Learn why the first five minutes matter and how to automate effective lead follow-up.

gohighlevel
crm
November 13, 2026

Connect a website form to GoHighLevel using native forms, webhooks, or the API. Includes Next.js code, field mapping, testing, and fixes.