Designing Tamper-Evident Key Backup JSONs: Versioning, Salt Rotation, and Order Binding

In end-to-end encryption (E2EE), zero-knowledge consulting delivery such as security audits and commercial due-diligence reports, and decentralized key management, users face a practical question: how can they safely recover their decryption private key after changing computers, reinstalling the system, or clearing browser storage?

Many client-side decryption designs let users download a local file such as {"privateKey": "0x1234..."}, or simply encrypt the key with a password and export an unstructured ciphertext JSON object:

// A vulnerable backup-format anti-pattern common in basic implementations
{
  "salt": "a1b2c3...",
  "iv": "d4e5f6...",
  "ciphertext": "7g8h9i..."
}

This crude format creates two serious production usability and security failures:

  1. The ciphertext-swapping trap and opaque decryption errors: a client who regularly buys due diligence or security audits may have 5 key-backup files for different orders, such as backup-1.json and backup-2.json. While opening the confidential report for order #07, they accidentally select order #03’s backup but enter their usual correct password. With no business context bound into the file, WebCrypto spends hundreds of milliseconds on expensive PBKDF2 derivation, then returns the uninformative OperationError: The operation failed for an operation-specific reason. The user cannot tell whether the password is wrong, the selected backup is wrong, or an attacker tampered with the server’s report.
  2. Public-key substitution attacks: an attacker who intercepts a backup can modify its plaintext fields, induce recovery against an attacker-supplied public key, and steal the result through a side channel during decryption.

The end-to-end confidential consulting protocol Fone ProofDesk defines a strict tamper-resistant, confusion-resistant ReadingKeyBackup schema. This article covers industrial-grade ASIC-resistant PBKDF2 with 310,000 iterations, binding the public-key URI through AES-GCM additional authenticated data, full AnswerContext business constraints, and millisecond preflight checks that avoid unnecessary derivation.


The Key Backup and Recovery State Machine

Designing Tamper-Evident Key Backup JSONs: Versioning, Salt Rotation, and Order Binding

ProofDesk confines the private-key lifecycle to browser memory. Only tamper-resistant encrypted envelopes circulate outside it:

+-----------------------------------------------------------------------------------+
|                      ProofDesk Key Backup and Context-Safe Recovery               |
+-----------------------------------------------------------------------------------+
|  1. Client-Side Key Generation                                                     |
|     - WebCrypto generates RSA-OAEP 2048-bit pair (public SPKI, private PKCS#8)     |
|     - Unique public-key identifier: publicKeyURI (Base64 JSON Data URI)           |
|     - Persist public key on-chain or with the order; private key stays in memory |
+-----------------------------------------------------------------------------------+
                                       |
                                       v
+-----------------------------------------------------------------------------------+
|  2. Envelope Encryption via PBKDF2 & AES-256-GCM                                   |
|     - User chooses a strong reading password (>= 12 characters)                    |
|     - PBKDF2-SHA256, 310,000 iterations + 16-byte high-entropy salt -> 256-bit KEK |
|     - Tamper protection: publicKeyURI becomes AES-GCM additionalData (AAD)        |
|     - Ciphertext structure: { version: 1, publicKeyURI, salt, iv, ciphertext }     |
+-----------------------------------------------------------------------------------+
                                       |
                                       v
+-----------------------------------------------------------------------------------+
|  3. Zero-Cost Preflight Metadata Verification                                      |
|     - File size limit: file.size <= 16,000 bytes (prevent memory bombs)           |
|     - Field and version assertion: backup.version === 1                           |
|     - Reject wrong-order files: backup.publicKeyURI === order.userPublicKeyURI   |
|       * Mismatch: "File does not belong to this order" (0ms; avoids 300ms PBKDF2) |
+-----------------------------------------------------------------------------------+
                                       |
                                       v
+-----------------------------------------------------------------------------------+
|  4. Context-Bound Decryption & On-Chain Integrity                                  |
|     - Password unlocks private key; AAD verifies publicKeyURI integrity            |
|     - Build AnswerContext: [chainId, escrow, orderId, questionHash]                |
|     - RSA-OAEP decrypts content key KEK (contextBytes label)                       |
|     - AES-GCM decrypts confidential content (contextBytes AAD)                     |
|     - On-chain hash check: answerCommitment(context, decrypted) === order.answerHash|
+-----------------------------------------------------------------------------------+

Comparing Three Key-Backup Approaches

Architecture dimension Plaintext private-key file (raw .pem or hexadecimal key) Simple password-encrypted blob (no metadata binding) ProofDesk tamper-resistant multicontext schema
Offline exposure protection None (finding the file gives full access) Good, depending on password strength Very high (310,000 PBKDF2 iterations resist offline brute force)
Wrong-file diagnosis 0 (cannot determine the file’s purpose) Very poor (generic OperationError misleads users into blaming the password) 100% precise (millisecond publicKeyURI comparison identifies a backup for another order)
Public-key tamper protection Unsupported Unsupported Strong verification (publicKeyURI in AES-GCM AAD; changes invalidate the tag)
Cross-order ciphertext substitution Unsupported Order A ciphertext can be presented for order B 100% immunity (AnswerContext binds chain ID, vault address, and order ID)
Private-key memory hygiene Exportable key remains in memory long-term Relies on garbage collection Imported non-extractable (extractable: false) and actively cleared after reading

Implementation 1: A Defined Schema and Additional Authenticated Data (answerEncryption.ts)

In proofdesk/frontend/src/lib/answerEncryption.ts, we strictly define the backup JSON structure:

// Excerpt from proofdesk/frontend/src/lib/answerEncryption.ts
export interface ReadingKeyBackup {
  version: 1;           // Format version for future backward compatibility
  publicKeyURI: string; // Corresponding public-key Data URI (business anchor)
  salt: string;         // Base64-encoded 16-byte random salt
  iv: string;           // Base64-encoded 12-byte AES-GCM random IV
  ciphertext: string;   // Base64-encoded encrypted private-key payload (PKCS#8)
}

const PUBLIC_PREFIX = "data:application/vnd.vpc.public-key+json;base64,";
const ITERATIONS = 310_000; // Iteration count following OWASP's recommended 2026 security standard

Why Use additionalData (AAD)?

Standard AES-CBC provides confidentiality but not integrity. Modern AES-GCM (Galois/Counter Mode) is authenticated encryption with associated data (AEAD). Alongside encrypting the main plaintext, it accepts additional plaintext data that does not need encryption (additionalData).

AES-GCM computes its authentication tag over both the ciphertext and additionalData. Therefore, if an attacker changes publicKeyURI, decryption fails its tag check even when the password is correct.

// Excerpt from proofdesk/frontend/src/lib/answerEncryption.ts
async function passwordKey(password: string, salt: Uint8Array) {
  // 1. Import raw password material
  const material = await crypto.subtle.importKey(
    "raw",
    encoder.encode(password),
    "PBKDF2",
    false,
    ["deriveKey"]
  );
  // 2. Derive a 256-bit AES-GCM key with 310,000 PBKDF2-SHA256 iterations
  return crypto.subtle.deriveKey(
    { name: "PBKDF2", hash: "SHA-256", salt, iterations: ITERATIONS },
    material,
    { name: "AES-GCM", length: 256 },
    false,
    ["encrypt", "decrypt"]
  );
}

export async function createReadingKey(password: string): Promise<ReadingKeyBackup> {
  if (password.length < 12) {
    throw new Error("Use a reading password of at least 12 characters");
  }

  // Generate a local RSA-OAEP 2048-bit key pair
  const pair = await crypto.subtle.generateKey(
    {
      name: "RSA-OAEP",
      modulusLength: 2048,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256",
    },
    true,
    ["encrypt", "decrypt"]
  );

  const [publicKey, privateKey] = await Promise.all([
    crypto.subtle.exportKey("spki", pair.publicKey),
    crypto.subtle.exportKey("pkcs8", pair.privateKey),
  ]);

  const publicKeyURI = jsonURI(PUBLIC_PREFIX, {
    version: 1,
    algorithm: "RSA-OAEP-256",
    spki: base64(publicKey),
  });

  const salt = random(16);
  const iv = random(12);
  const key = await passwordKey(password, salt);

  // Core security boundary: bind publicKeyURI into AES-GCM additionalData
  const ciphertext = await crypto.subtle.encrypt(
    {
      name: "AES-GCM",
      iv,
      additionalData: encoder.encode(publicKeyURI),
    },
    key,
    privateKey
  );

  return {
    version: 1,
    publicKeyURI,
    salt: base64(salt),
    iv: base64(iv),
    ciphertext: base64(ciphertext),
  };
}

When decrypting and recovering the private key, the system verifies the same publicKeyURI as additionalData, ensuring no third party has altered the mathematical correspondence between the private and public keys:

// Excerpt from proofdesk/frontend/src/lib/answerEncryption.ts
export async function unlockReadingKey(
  backup: ReadingKeyBackup,
  password: string
): Promise<CryptoKey> {
  // Strict preliminary allowlist validation
  if (
    backup.version !== 1 ||
    !isReadingKeyURI(backup.publicKeyURI) ||
    JSON.stringify(backup).length > 16_000
  ) {
    throw new Error("Invalid reading key backup");
  }

  const key = await passwordKey(password, unbase64(backup.salt));
  
  // Decrypt and automatically verify the tag and AAD
  const raw = await crypto.subtle.decrypt(
    {
      name: "AES-GCM",
      iv: unbase64(backup.iv),
      additionalData: encoder.encode(backup.publicKeyURI),
    },
    key,
    unbase64(backup.ciphertext)
  );

  // Import recovered private key as non-extractable (extractable: false) to prevent further exposure
  return crypto.subtle.importKey(
    "pkcs8",
    raw,
    { name: "RSA-OAEP", hash: "SHA-256" },
    false,
    ["decrypt"]
  );
}

Implementation 2: Binding the Full Business Context (AnswerContext)

The backup itself needs tamper protection, and the consultant’s encrypted deliverable must also resist substitution across orders.

Suppose a consultant predicts “Team A wins” in order #01 and “Team B wins” in order #02. If an attacker intercepts the encrypted package for #01 and submits it as the deliverable for #02 to another client, how does the system detect that?

ProofDesk introduces an immutable business-context digest (AnswerContext):

// Excerpt from proofdesk/frontend/src/lib/answerEncryption.ts
export interface AnswerContext {
  chainId: number;
  escrow: string;
  orderId: string;
  questionHash: string;
  questionType: number;
}

function contextBytes(context: AnswerContext): Uint8Array {
  // Fix the version, chain ID, escrow contract address, order ID, and question hash
  return encoder.encode(
    JSON.stringify([
      1,
      context.chainId,
      context.escrow.toLowerCase(),
      context.orderId,
      context.questionHash.toLowerCase(),
      context.questionType,
    ])
  );
}

When encrypting the deliverable:

  1. AES-GCM layer: use contextBytes as the confidential content’s additionalData;
  2. RSA-OAEP layer: use contextBytes as the asymmetric key-wrapping label.

This means moving a report to another chain, another vault contract, or even changing one digit of the order ID makes decryption fail because the RSA label or AES authentication tag does not match. Ciphertext substitution is prevented at the cryptographic layer.


Implementation 3: Millisecond Preflight Checks Without Derivation (AnswerReader.tsx)

PBKDF2’s 310,000 hashes have a usability cost: while resisting brute force, they require roughly 100~300 milliseconds of CPU-intensive work on ordinary phones and low-end computers.

If a user uploads a backup for the wrong order, blocking for 300 milliseconds to derive a key before reporting decryption failure creates a poor experience.

In proofdesk/frontend/src/features/orders/AnswerReader.tsx, we implement a zero-cost metadata preflight check while reading the file:

// Excerpt from proofdesk/frontend/src/features/orders/AnswerReader.tsx
  const importKey = async (file?: File) => {
    if (!file) return;
    setError("");
    try {
      // 1. File-size guard: private-key backup JSON cannot exceed 16KB (prevent large-file OOM attacks)
      if (file.size > 16_000) {
        throw new Error("Backup too large");
      }

      const key: ReadingKeyBackup = JSON.parse(await file.text());

      // 2. Fast millisecond assertion: backup publicKeyURI must exactly match the current on-chain order's key
      if (key.version !== 1 || key.publicKeyURI !== order.userPublicKeyURI) {
        throw new Error("Wrong backup"); // Wrong backup file: reject immediately in 0 milliseconds
      }

      setImported(key);
    } catch {
      setImported(null);
      // Tell the user precisely: "Invalid file, or key backup does not belong to this order"
      setError(t("importFailed"));
    }
  };

With this check:

  • A wrong file immediately produces a clear message in 0 milliseconds: “This backup does not belong to this order. Select the corresponding backup”;
  • Only when the backup matches the order does the system request a password and perform expensive PBKDF2 derivation;
  • A wrong password then produces an explicit password error, separating wrong-file and wrong-password failures.

Automated Test Evidence

In proofdesk/frontend/src/lib/answerEncryption.test.ts, comprehensive cryptographic assertions verify robustness against tampering and cross-context attacks:

// Excerpt from proofdesk/frontend/src/lib/answerEncryption.test.ts
describe("encrypted consultation delivery", () => {
  // 1. Verify wrong passwords are rejected and backup JSON contains no plaintext strings
  it("protects the backup and rejects a wrong password", async () => {
    const backup: ReadingKeyBackup = await createReadingKey(password);
    expect(JSON.stringify(backup)).not.toContain('"d"'); // Ensure no plaintext private-key parameter is present
    await expect(unlockReadingKey(backup, "wrong-password")).rejects.toThrow();
  });

  // 2. Verify cross-order and cross-chain ciphertext substitution is blocked
  it.each([
    { ...context, orderId: "8" }, // Tamper with order ID
    { ...context, chainId: 1 },    // Tamper with chain ID
    { ...context, escrow: "0x2222222222222222222222222222222222222222" }, // Tamper with vault contract
    { ...context, questionHash: `0x${"56".repeat(32)}` }, // Tamper with question digest
  ])("rejects ciphertext from a different order context: %j", async (otherContext) => {
    const backup: ReadingKeyBackup = await createReadingKey(password);
    const uri = await encryptAnswer(backup.publicKeyURI, context, report);
    const key = await unlockReadingKey(backup, password);
    // Attempt decryption with the wrong context; assert 100% failure
    await expect(decryptAnswer(uri, key, otherContext, sportsHash)).rejects.toThrow();
  });

  // 3. Verify changing publicKeyURI invalidates the AES-GCM authentication tag
  it("rejects modified publicKeyURI in backup", async () => {
    const backup: ReadingKeyBackup = await createReadingKey(password);
    const other = await createReadingKey(password);
    // Maliciously replace the backup's public-key URI
    await expect(
      unlockReadingKey({ ...backup, publicKeyURI: other.publicKeyURI }, password)
    ).rejects.toThrow();
  });
});

Four Engineering Rules for Production Key Backups

  1. Never export plaintext private keys to storage: after generating the pair, immediately encrypt exported PKCS#8 bytes with a password-derived key in the same memory context. Unencrypted private-key bytes must never reach disk;
  2. Bind unique business credentials into AAD: whether protecting a key or ciphertext, use AES-GCM additionalData to include publicKeyURI or orderId in tag verification and prevent mismatches;
  3. Check metadata before expensive hashing: compare file size, version, and public-key fingerprint first. Reject wrong-file mistakes in 0 milliseconds instead of wasting mobile CPU resources;
  4. Keep recovered keys non-extractable: when restoring the private key with crypto.subtle.importKey, explicitly set extractable to false, preventing subsequently injected third-party scripts from stealing it through exportKey.

Enterprise Zero-Trust Confidential Delivery Consulting

Fone provides zero-trust, end-to-end encrypted report delivery and key custody for code auditors, law firms, financial due-diligence teams, and Web3 prediction protocols. Fone ProofDesk has implemented the full production lifecycle from client-side WebCrypto encryption and smart-contract staking to decentralized commitment verification: