Skip to content

feat(crypto): upgrade keystore encryption to AES-256-CTR (v2) - #1723

Open
betelthyme wants to merge 1 commit into
masterfrom
feat/crypto-aes256-keystore
Open

feat(crypto): upgrade keystore encryption to AES-256-CTR (v2)#1723
betelthyme wants to merge 1 commit into
masterfrom
feat/crypto-aes256-keystore

Conversation

@betelthyme

@betelthyme betelthyme commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

Summary

Fixes #1720.

Upgrades @xchainjs/xchain-crypto keystore encryption from AES-128-CTR to AES-256-CTR, introducing keystore format version 2. The previous scheme derived 32 bytes via PBKDF2 but used only the first 16 as the AES key (aes-128-ctr), with bytes 16–32 as the MAC key. We now derive 64 bytes and split them into an independent 32-byte AES-256 key and 32-byte MAC key.

What changed (src/crypto.ts)

  • Constants: cipher aes-128-ctraes-256-ctr; dklen 3264; new keystoreVersion = 2.
  • New aesKeyLengthForCipher(cipherName) helper — maps cipher → AES key length (16 for aes-128, 32 for aes-256), throws on unsupported ciphers.
  • encryptToKeyStore: splits the derived key into encryptionKey = slice(0, keyLen) and macKey = slice(keyLen, dklen), and stamps version: 2.
  • decryptFromKeystore: derives the same split from the keystore's own cipher/dklen fields, so the byte layout is data-driven rather than hard-coded.

Notable design decisions

  • Independent MAC key (not key reuse). With a 32-byte AES-256 key, naively reusing slice(16,32) as the MAC key would make the MAC key a substring of the encryption key — key reuse across two primitives. Instead dklen is raised to 64 so the AES key (0–32) and MAC key (32–64) never overlap.
  • Source of truth for the key split is cipher/dklen, not version. Those fields literally determine the byte layout and are already stored in every keystore; version is the coarse label. This is what keeps decryption of both formats correct.

Backward compatibility

  • Reading old files: existing v1 (aes-128-ctr, dklen 32) keystores decrypt unchanged — covered by tests. No migration needed for existing wallets.
  • ⚠️ Writing new files (forward-incompatible): keystores newly created by this version are v2 and cannot be opened by older xchain-crypto releases (old code hard-codes a 16-byte key slice and throws on a 32-byte AES-256 key). Existing files are untouched. Integrators sharing keystore files across components on different xchain-crypto versions should upgrade them together before creating new keystores. Called out in the changeset.

Tests (__tests__/crypto.test.ts)

  • New v2 known-answer test — deterministic salt/iv produce a locked-in ciphertext + MAC (locks the v2 format).
  • New v2 decrypt test.
  • Preserved v1 backward-compat decrypt fixtures (both aes-128-ctr c=600000 and the older c=262144).
  • Export Keystore test updated to assert aes-256-ctr / dklen 64 / version 2.

All 14 tests pass; build, tsc --noEmit, and eslint are clean.

Security / compatibility notes

Changeset

minor bump for @xchainjs/xchain-crypto.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added support for a newer, stronger keystore format using AES-256 encryption.
    • Newly created keystores now use an updated version format.
  • Bug Fixes

    • Existing keystores from the previous format remain readable.
    • Import/export behavior now correctly handles both older and newer keystore formats.

encryptToKeyStore now derives a 64-byte key (dklen 32 -> 64) and splits
it into an independent 32-byte AES-256 key and 32-byte MAC key, writing
cipher "aes-256-ctr" and version 2. Previously only the first 16 of 32
derived bytes were used, with aes-128-ctr.

decryptFromKeystore derives the AES-key/MAC-key split from the keystore's
own cipher and dklen, so existing v1 (aes-128-ctr) keystores still decrypt
unchanged. Files newly written are v2 and cannot be read by older
xchain-crypto releases (forward-incompatible write; documented in changeset).

Tests: v2 known-answer (ciphertext + mac) test, v2 decrypt, and preserved
v1 backward-compat decrypt fixtures. All 14 tests pass; build, typecheck,
and lint clean.

Closes #1720

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR upgrades xchain-crypto keystore encryption from AES-128-CTR (v1) to AES-256-CTR (v2), increasing PBKDF2 dklen from 32 to 64 and splitting the derived key into separate AES and MAC keys via a new aesKeyLengthForCipher helper. Decryption remains backward-compatible with v1 keystores. Tests and a changeset were updated accordingly.

Changes

Keystore v2 encryption/decryption

Layer / File(s) Summary
v2 constants and key-length helper
packages/xchain-crypto/src/crypto.ts
Replaces v1 constants (aes-128-ctr, dklen 32, version 1) with v2 defaults and adds aesKeyLengthForCipher to compute AES key size per cipher, erroring on unsupported ciphers.
Encryption: dynamic key splitting and version write
packages/xchain-crypto/src/crypto.ts
encryptToKeyStore splits derivedKey into AES/MAC keys dynamically, uses the AES key in cipher initialization, and writes keystoreVersion (2) instead of a hardcoded version.
Decryption: backward-compatible dynamic key splitting
packages/xchain-crypto/src/crypto.ts
decryptFromKeystore derives AES/MAC keys dynamically from the keystore's own cipher field, verifies MAC with the derived macKey, and decrypts using the derived encryptionKey.
Tests and changeset
packages/xchain-crypto/__tests__/crypto.test.ts, .changeset/crypto-aes256-keystore.md
Adds expectedKeystoreV2 fixture, updates encryption/decryption/export tests for v2 cipher/dklen/version, and documents the format change, backward-compatible decryption, and forward incompatibility.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers: Thorian1te

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: upgrading keystore encryption to AES-256-CTR with a v2 format.
Linked Issues check ✅ Passed The changes match the issue: new AES-256-CTR encryption, a 64-byte split key layout, v2 versioning, and backward-compatible decryption for v1 keystores.
Out of Scope Changes check ✅ Passed The PR stays focused on the keystore encryption upgrade, with only expected tests and release notes added.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/crypto-aes256-keystore

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/xchain-crypto/src/crypto.ts (1)

212-226: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Validate dklen against AES key length to prevent empty MAC key.

If a malformed or crafted keystore has dklen <= aesKeyLength (e.g., cipher: 'aes-256-ctr' with dklen: 32), macKey would be an empty buffer. The MAC would then be blake2b(ciphertext) — independent of the password — so any password would pass the MAC check and proceed to decryption, returning garbage instead of an Invalid password error. Adding a guard in decryptFromKeystore closes this edge case.

🛡️ Proposed validation in decryptFromKeystore
   const aesKeyLength = aesKeyLengthForCipher(keystore.crypto.cipher)
+  if (kdfparams.dklen < aesKeyLength + 16) {
+    throw new Error('Invalid keystore: derived key length too short for cipher')
+  }
   const encryptionKey = derivedKey.slice(0, aesKeyLength)
   const macKey = derivedKey.slice(aesKeyLength, kdfparams.dklen)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/xchain-crypto/src/crypto.ts` around lines 212 - 226, In
decryptFromKeystore, add a validation after deriving aesKeyLength and before
slicing derivedKey to ensure kdfparams.dklen is greater than the AES key length
for keystore.crypto.cipher. If dklen is too small (which would make macKey
empty), reject the keystore with an Invalid password or malformed keystore error
instead of continuing to MAC verification and decryption. Use the existing
aesKeyLengthForCipher, derivedKey, and constantTimeEqual flow as the location
for the guard.
🧹 Nitpick comments (1)
packages/xchain-crypto/__tests__/crypto.test.ts (1)

87-108: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider adding a v2 wrong-password rejection test.

The wrong-password test at Line 118 only exercises the v1 MAC path. Since v2 uses a 32-byte MAC key (vs 16 bytes in v1), a v2 wrong-password assertion would verify the updated MAC computation rejects incorrect passwords.

🧪 Suggested additional test
+  it('decryptFromKeystore() should reject an incorrect password for v2', async () => {
+    await expect(decryptFromKeystore(expectedKeystoreV2, 'wrong-password')).rejects.toThrow('Invalid password')
+  })
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/xchain-crypto/__tests__/crypto.test.ts` around lines 87 - 108, Add a
negative test for encryptToKeyStore()/decryptFromKeystore() that uses the v2
aes-256-ctr fixture and a wrong password, since the existing rejection test only
covers the legacy v1 path. Reuse the existing v2 test data and assert that
decryptFromKeystore rejects incorrect credentials so the v2 MAC computation
(with the 32-byte key path) is exercised and verified.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@packages/xchain-crypto/src/crypto.ts`:
- Around line 212-226: In decryptFromKeystore, add a validation after deriving
aesKeyLength and before slicing derivedKey to ensure kdfparams.dklen is greater
than the AES key length for keystore.crypto.cipher. If dklen is too small (which
would make macKey empty), reject the keystore with an Invalid password or
malformed keystore error instead of continuing to MAC verification and
decryption. Use the existing aesKeyLengthForCipher, derivedKey, and
constantTimeEqual flow as the location for the guard.

---

Nitpick comments:
In `@packages/xchain-crypto/__tests__/crypto.test.ts`:
- Around line 87-108: Add a negative test for
encryptToKeyStore()/decryptFromKeystore() that uses the v2 aes-256-ctr fixture
and a wrong password, since the existing rejection test only covers the legacy
v1 path. Reuse the existing v2 test data and assert that decryptFromKeystore
rejects incorrect credentials so the v2 MAC computation (with the 32-byte key
path) is exercised and verified.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 39c6b67b-043a-43a9-b52b-688b3b0c6d1c

📥 Commits

Reviewing files that changed from the base of the PR and between aa96ac0 and 317d713.

📒 Files selected for processing (3)
  • .changeset/crypto-aes256-keystore.md
  • packages/xchain-crypto/__tests__/crypto.test.ts
  • packages/xchain-crypto/src/crypto.ts

@Thorian1te
Thorian1te requested a review from Naq302 July 20, 2026 05:54
@Thorian1te

Copy link
Copy Markdown
Collaborator

Security take: not urgent

v1 is not practically “hackable” relative to v2 today. AES-128-CTR has no known practical break for this use case; the real offline risk for both formats is a weak password + stolen keystore file, not AES width. v2 mainly adds long-term/quantum margin and ~2× PBKDF2 cost per guess (dklen 64 vs 32). Shared gaps (e.g. MAC not binding the IV — #1721) affect both.

Defer / skip Still worth merging later
No live AES-128 break AES-256 is the expected standard for seed storage
Dominant risk is password / device compromise Modest extra offline-crack cost + future margin
Forward-incompatible writes (old clients can’t open new v2 keystores) Work is already done + tested

Bottom line: safe to wait if prioritization is tight — this is modernization/hygiene, not a must-ship patch. If/when it ships, call out the integrator note: upgrade all components that share keystore files before creating new ones.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

xchain-crypto: keystore uses aes-128-ctr (only 16 of 32 derived bytes); consider aes-256-ctr

3 participants