
In high-stakes technical consulting, security audits, and financial advisory, delivering confidential research reports over standard Web2 storage or unencrypted cloud portals creates severe legal and operational liabilities. If the backend database or object store is breached, sensitive customer findings are exposed in cleartext. In Fone ProofDesk, this exposure is eliminated through a zero-knowledge delivery architecture: generating asymmetric RSA-OAEP reading keypairs directly in the client’s browser, encapsulating report payloads in ephemeral AES-256-GCM symmetric envelopes bound to on-chain escrow orders, reconciling off-chain plaintext with on-chain cryptographic commitments, and enabling cross-device access recovery via password-derived PBKDF2 key backup files.
1. The Production Threat Model: Why Plaintext Advisory Portals Fail
Security consulting firms, legal practices, and Web3 audit studios routinely deliver vulnerability assessments, strategic advisory memos, and proprietary market predictions.
In conventional consulting platforms, the architecture relies on server-managed access controls:
- Consultant writes a report and uploads it to an S3 bucket or relational database.
- The server authenticates the customer via JWT / session cookie and serves the file over HTTPS.
This conventional model collapses under three real-world threat scenarios:
[Threat Scenario 1: The Database / Object Store Breach]
- A malicious actor compromises the application server or gains read access to S3/database backups.
- Impact: All historical client vulnerability reports, proprietary research, and strategic M&A memos
stored in cleartext are leaked simultaneously. Total compromise of firm confidentiality.
[Threat Scenario 2: The Malicious or Compromised Insider]
- An internal database administrator or rogue employee queries the advisory orders table.
- Impact: The employee accesses unreleased security exploit details before patches are deployed.
[Threat Scenario 3: Deliverable Tampering and Repudiation]
- An advisor delivers an ambiguous recommendation. When challenged, the advisor alters the stored
database record post-facto.
- Impact: Without on-chain cryptographic commitment hashes, neither client nor advisor can prove
what exact text was delivered at the agreed deadline.
To achieve true confidentiality, the platform must enforce a Zero-Knowledge Data Plane:
- The server (and smart contract) must never observe the plaintext report or the decryption private key.
- The buyer’s browser generates the reading keypair locally before placing the order.
- The advisor’s browser encrypts the report using the buyer’s public key before submitting the transaction.
- The buyer’s browser decrypts the deliverable locally and validates an immutable cryptographic commitment hash against the on-chain smart contract before rendering the text.
2. Cryptographic Envelope Architecture: Asymmetric Wrapping + AES-256-GCM

In frontEnd/src/lib/answerEncryption.ts, the cryptographic pipeline is built entirely on native browser primitives using the Web Crypto API (window.crypto.subtle), avoiding bloated third-party dependencies.
+----------------------------------------------------------------------------------------------------+
| BUYER KEY SETUP (PHASE 1) |
| |
| [ Buyer Browser ] |
| 1. Generate RSA-OAEP 2048-bit Keypair (SHA-256) |
| 2. Export Public Key -> Format as Data URI (publicKeyURI) |
| 3. Prompt User for Reading Password (min 12 chars) |
| 4. Derive KEK via PBKDF2-SHA-256 (310,000 iterations, 16-byte random salt) |
| 5. Encrypt Private Key via AES-256-GCM with additionalData = publicKeyURI |
| 6. Export ReadingKeyBackup JSON (publicKeyURI, salt, iv, ciphertext) |
+----------------------------------------------------------------------------------------------------+
|
| Order Placement with publicKeyURI
v
+----------------------------------------------------------------------------------------------------+
| CONSULTANT ENCRYPTION (PHASE 2) |
| |
| [ Consultant Browser ] |
| 1. Import Buyer Public Key from publicKeyURI |
| 2. Generate Ephemeral Symmetric DEK (AES-256-GCM, 256-bit) |
| 3. Construct AnswerContext bytes: [version, chainId, escrow, orderId, questionHash, type] |
| 4. Encrypt Report Payload via AES-256-GCM (IV: 12 bytes, additionalData: AnswerContext) |
| 5. Wrap DEK via RSA-OAEP (with label = AnswerContext) using Buyer Public Key |
| 6. Pack Envelope: wrappedKey, iv, ciphertext -> encryptedAnswerURI |
| 7. Compute on-chain commitment: keccak256(orderId, encodedAnswer, salt) |
| 8. Submit to Smart Contract: submitAnswer(orderId, answerHash, encryptedAnswerURI) |
+----------------------------------------------------------------------------------------------------+
|
| On-Chain Event / Order Query
v
+----------------------------------------------------------------------------------------------------+
| BUYER DECRYPTION (PHASE 3) |
| |
| [ Buyer Browser ] |
| 1. Unlock ReadingKeyBackup with Password -> Recover Private Key via WebCrypto |
| 2. Unwrap DEK using RSA-OAEP with label = AnswerContext |
| 3. Decrypt Payload via AES-256-GCM with additionalData = AnswerContext |
| 4. Compute Local Commitment: keccak256(orderId, encodedAnswer, salt) |
| 5. Assert localCommitment == order.answerHash from Smart Contract |
| 6. Render Plaintext Report in Isolated Memory Buffer (Zero Server Storage) |
+----------------------------------------------------------------------------------------------------+
3. Client-Side Implementation: Keypair Generation and Password Backup
In frontEnd/src/lib/answerEncryption.ts:L1-L98, the reading key backup format is strictly defined as an immutable JSON structure:
export interface ReadingKeyBackup {
version: 1;
publicKeyURI: string;
salt: string;
iv: string;
ciphertext: string;
}
const PUBLIC_PREFIX = "data:application/vnd.vpc.public-key+json;base64,";
const ANSWER_PREFIX = "data:application/vnd.vpc.answer+json;base64,";
const ITERATIONS = 310_000;
Keypair Generation and Password Key Derivation
When a buyer prepares an order, createReadingKey generates an RSA-OAEP 2048-bit keypair and locks the private key using AES-GCM derived from the user’s password (src/lib/answerEncryption.ts:L37-L58):
async function passwordKey(password: string, salt: Uint8Array<ArrayBuffer>) {
const material = await crypto.subtle.importKey(
"raw",
encoder.encode(password),
"PBKDF2",
false,
["deriveKey"]
);
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");
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), iv = random(12);
const key = await passwordKey(password, salt);
// Encrypt PKCS#8 private key, binding publicKeyURI as additional authenticated data (AAD)
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)
};
}
Notice the security design in step 5: additionalData: encoder.encode(publicKeyURI). The public key URI is embedded directly into the GCM authentication tag. If an attacker tampers with the public key URI in the backup file, AES-GCM decryption fails immediately during tag verification.
Key Recovery Across Devices
When the buyer switches browsers or accesses the platform from a new laptop, the private key is not in localStorage.
In src/lib/answerEncryption.ts:L59-L67, unlockReadingKey reconstructs the private key using the backup file and password:
export async function unlockReadingKey(backup: ReadingKeyBackup, password: string): Promise<CryptoKey> {
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));
const raw = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: unbase64(backup.iv), additionalData: encoder.encode(backup.publicKeyURI) },
key,
unbase64(backup.ciphertext)
);
// Import private key as non-extractable (extractable: false)
return crypto.subtle.importKey("pkcs8", raw, { name: "RSA-OAEP", hash: "SHA-256" }, false, ["decrypt"]);
}
By specifying extractable: false when importing into WebCrypto, browser extensions and third-party scripts cannot export the raw private key bytes from memory.
4. Context Binding & On-Chain Commitment Verification
A critical vulnerability in client-side encryption is the Ciphertext Replay Attack: an attacker copies an encrypted answer from Order #1 and submits it as the deliverable for Order #2 on a different network.
To eliminate this vulnerability, Fone ProofDesk computes a cryptographically strict AnswerContext bound as Additional Authenticated Data (src/lib/answerEncryption.ts:L68-L98):
function contextBytes(context: AnswerContext) {
return encoder.encode(
JSON.stringify([
1,
context.chainId,
context.escrow.toLowerCase(),
context.orderId,
context.questionHash.toLowerCase(),
context.questionType
])
);
}
export async function encryptAnswer(
uri: string,
context: AnswerContext,
answer: ConsultationAnswer
): Promise<string> {
validateAnswer(context, answer);
const publicData = readURI(uri, PUBLIC_PREFIX);
const publicKey = await crypto.subtle.importKey(
"spki",
unbase64(publicData.spki),
{ name: "RSA-OAEP", hash: "SHA-256" },
false,
["encrypt"]
);
// Ephemeral symmetric Data Encryption Key (DEK)
const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]);
const iv = random(12), additionalData = contextBytes(context);
const [ciphertext, wrappedKey] = await Promise.all([
// 1. Encrypt payload with DEK, bound to context
crypto.subtle.encrypt(
{ name: "AES-GCM", iv, additionalData },
key,
encoder.encode(JSON.stringify(answer))
),
// 2. Wrap DEK with Buyer Public Key, bound to context via RSA-OAEP label
crypto.subtle.exportKey("raw", key).then(raw =>
crypto.subtle.encrypt({ name: "RSA-OAEP", label: additionalData }, publicKey, raw)
),
]);
return jsonURI(ANSWER_PREFIX, {
version: 1,
algorithm: "RSA-OAEP-256+A256GCM",
wrappedKey: base64(wrappedKey),
iv: base64(iv),
ciphertext: base64(ciphertext)
});
}
Decryption and On-Chain Hash Verification
When decrypting the answer, the buyer’s browser executes two independent integrity checks:
- Cryptographic Context Check: The RSA-OAEP label and AES-GCM authentication tag are verified against the local
AnswerContext(incorporatingchainIdandescrowAddress). - On-Chain Commitment Hash Match: The decrypted prediction and salt are hashed and asserted against
order.answerHashstored inConsultationEscrow.sol:
export function answerCommitment(context: AnswerContext, answer: ConsultationAnswer): `0x${string}` {
validateAnswer(context, answer);
const encoded = context.questionType === 0
? encodeAbiParameters([{ type: "bool" }], [answer.prediction as boolean])
: encodeAbiParameters([{ type: "uint8" }], [answer.prediction as number]);
return keccak256(
encodeAbiParameters(
[{ type: "uint256" }, { type: "bytes" }, { type: "bytes32" }],
[BigInt(context.orderId), encoded, answer.salt]
)
);
}
// In decryptAnswer:
if (answerCommitment(context, answer).toLowerCase() !== hash.toLowerCase()) {
throw new Error("Answer does not match the on-chain commitment");
}
If the advisor modified the deliverable text, or if the ciphertext was tampered with in transit, the commitment hash does not match, preventing the display of fraudulent reports.
5. Smart Contract Escrow State Machine: ConsultationEscrow.sol
The financial settlement is governed by ConsultationEscrow.sol:L68-L118, holding the USDC deposit in escrow until the deliverable is validated:
enum OrderStatus {
Created, // Funds locked in escrow, awaiting consultant answer
Answered, // Encrypted answer URI and hash committed by consultant
DisputeRequested, // Reserved for asynchronous oracle disputes
Resolving, // Settlement in progress
Refunded, // Answer incorrect; funds returned to buyer
Settled, // Answer correct or undisputed; funds released to consultant
Cancelled // Deadline expired without answer; buyer refunded
}
struct Order {
address user;
address consultant;
address paymentToken;
uint256 amount;
QuestionType questionType;
OrderStatus status;
bytes32 questionHash;
bytes32 answerHash;
string encryptedAnswerURI;
string userPublicKeyURI;
uint256 createdAt;
uint256 answerDeadline;
uint256 resolveTime;
uint256 disputeDeadline;
uint256 disputeWindow;
bytes encodedQuestionData;
bool priceSnapshotTaken;
bool priceActualOutcome;
int256 snapshotOraclePrice;
uint80 snapshotRoundId;
uint256 snapshotUpdatedAt;
}
The Settle and Dispute Flow
- Timeout Cancellation: If the consultant fails to submit an answer before
answerDeadline,cancelUnanswered(L375-L388) allows the buyer to withdraw their USDC without penalty. - Commitment Submission: In
submitAnswer(L305-L325), the consultant submitsanswerHashandencryptedAnswerURI.order.statustransitions fromCreatedtoAnswered. - Settlement: After
disputeDeadlinepasses, if no dispute is lodged,settle(orderId)releases the payment (minus platform fee) to the consultant.
6. Concrete Verification: Cryptographic Unit & E2E Tests
The security guarantees of Fone ProofDesk are proven in automated test suites:
Unit Suite (frontEnd/src/lib/answerEncryption.test.ts:L1-L68)
- Rejection of wrong passwords (
PBKDF2tag mismatch). - Dynamic randomness validation: Two consecutive encryptions of the same payload yield distinct ciphertexts (
expect(first).not.toBe(second)). - Rejection of cross-order context tampering (verifying that modifying
orderIdorchainIdthrows a WebCrypto error). - Rejection of modified ciphertext bits (verifying AES-GCM authentication tag integrity).
it("rejects modified ciphertext or a prediction that does not match the chain", async () => {
const backup: ReadingKeyBackup = await createReadingKey(password);
const uri = await encryptAnswer(backup.publicKeyURI, context, report);
const envelope = JSON.parse(atob(uri.split(",")[1]));
// Flip a single bit in the base64 ciphertext
envelope.ciphertext = (envelope.ciphertext[0] === "A" ? "B" : "A") + envelope.ciphertext.slice(1);
const tampered = uri.split(",")[0] + "," + btoa(JSON.stringify(envelope));
const key = await unlockReadingKey(backup, password);
await expect(decryptAnswer(tampered, key, context, sportsHash)).rejects.toThrow();
});
End-to-End Test (frontEnd/e2e/encrypted-price.spec.ts:L14-L45)
Verifies that reading passwords are never persisted to storage:
test("custom reading password survives a form refresh without being persisted or sending a transaction", async ({ page }) => {
await page.goto("/zh-CN/create/sports");
await page.getByLabel("设置阅读密码", { exact: true }).fill("my-private-reading-password");
await page.getByRole("button", { name: "生成阅读密钥", exact: true }).click();
// Verify localStorage and sessionStorage contain NO password plaintext
expect(await page.evaluate(() => JSON.stringify({ ...localStorage, ...sessionStorage })))
.not.toContain("my-private-reading-password");
});
7. Architectural Comparison: Report Delivery Systems
| Architectural Dimension | Traditional S3 / Cloud Portal | PGP / GPG Email Delivery | Fone ProofDesk Architecture |
|---|---|---|---|
| Server Knowledge | Full cleartext visibility | Metadata visible; PGP key friction | Zero-Knowledge (Encrypted client-side) |
| Key Generation Friction | Username / Password | GPG command-line setup | One-click browser WebCrypto keypair |
| Tamper Evidence | Database audit logs (Alterable) | Detached signatures | Immutable on-chain keccak256 commitment |
| Cross-Order Replay Defense | Application role check | None (Message is static) | Context-bound AAD (Chain ID, Order ID, Escrow) |
| Cross-Device Recovery | Password reset email | Import private .asc key |
Portable PBKDF2 Key Backup JSON |
| Financial Settlement | Invoicing / Stripe hold | Manual wires | Atomic smart contract escrow lock |
8. Integration & Commercial Next Steps
Confidential advisory delivery requires treating client data as strictly zero-trust. Delegating document security to standard cloud storage leaves advisory firms exposed to credential leaks, server compromises, and deliverable disputes.
The architecture implemented in Fone ProofDesk demonstrates how WebCrypto primitives, portable key backups, and EVM escrow contracts combine to deliver institutional confidentiality with standard web browser ergonomics.
Recommended Implementation Roadmap:
- Audit Sensitive Client Deliverables: Review whether your firm’s technical audit reports, legal memos, or financial assessments are currently stored in cleartext in Web2 databases or cloud drives.
- Review Advisory Delivery Guidelines: Explore our companion engineering guides on Modeling Delivery Deadlines in a Paid Advisory Platform and Recovering Encrypted Deliverables on a New Device.
- Explore the Working Product: Review the screen captures and verified workflows on the Fone ProofDesk Product Page or explore our Rules & Customization Architecture.
- Schedule an Architecture Consultation: If your organization delivers security audits, proprietary research, or institutional advisory services requiring verifiable encrypted escrow, book a technical demo walkthrough or request an implementation proposal.