Building FileBee: End-to-End Encrypted File Sharing with Zero-Knowledge Architecture
Building FileBee: End-to-End Encrypted File Sharing with Zero-Knowledge Architecture
Introduction: The Privacy Problem in File Sharing
When you upload a file to most cloud storage or file-sharing services, there's an uncomfortable truth: the company can access your data. Whether it's Dropbox, Google Drive, WeTransfer, or others, these platforms hold the encryption keys to your files. They can decrypt, scan, and access your content—for compliance, legal requests, or internal purposes.
This creates a fundamental trust problem. You're not just trusting their security infrastructure; you're trusting their policies, their employees, and their response to government requests.
I wanted to build something different. A file-sharing platform where even I, the developer, genuinely cannot access user files. Not "choose not to," but technically cannot.
That's how FileBee was born.
What is Zero-Knowledge Architecture?
Zero-knowledge architecture means the service provider has zero knowledge of the user's data. In the context of file sharing:
Files are encrypted on the client (in the browser) before upload
Encryption keys never leave the user's device
The server only stores encrypted blobs it cannot decrypt
If users lose their keys, files are permanently inaccessible—even to the service
This isn't just a privacy feature; it's a fundamental architectural guarantee.
The Technical Stack
Here's what powers FileBee:
Frontend: Angular 15+
Encryption: Web Crypto API (AES-256-GCM)
Key Storage: IndexedDB (client-side)
File Storage: Cloud Storage (encrypted blobs)
UI Framework: Angular Material
Build Tool: Angular CLI with production optimizations
Why These Choices?
Angular: Robust framework with excellent TypeScript support and built-in dependency injection
Web Crypto API: Native browser encryption with hardware acceleration, no external crypto libraries needed
IndexedDB: Persistent client-side storage for encryption keys with good browser support
Angular Material: Production-ready UI components with accessibility built-in
Core Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ User's Browser │
│ ┌────────────────────────────────────────────────────┐ │
│ │ 1. File Selection │ │
│ │ 2. Key Generation/Retrieval (IndexedDB) │ │
│ │ 3. Client-Side Encryption (Web Crypto API) │ │
│ │ 4. Upload Encrypted Blob │ │
│ └────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ FileBee Server │
│ ┌────────────────────────────────────────────────────┐ │
│ │ 1. Receive Encrypted Blob │ │
│ │ 2. Store in Cloud Storage │ │
│ │ 3. Generate Short URL │ │
│ │ 4. Return URL + QR Code │ │
│ └────────────────────────────────────────────────────┘ │
│ │
│ Note: Server never sees encryption keys or │
│ unencrypted file contents │
└─────────────────────────────────────────────────────────────┘
Implementation Deep Dive
1. Encryption Key Generation
FileBee uses AES-256-GCM (Galois/Counter Mode), which provides both confidentiality and authenticity:
typescript
async generateEncryptionKey(): Promise<CryptoKey> {
return await window.crypto.subtle.generateKey(
{
name: 'AES-GCM',
length: 256 // 256-bit key
},
true, // extractable: true (so we can export/import)
['encrypt', 'decrypt'] // key usages
);
}
Why AES-GCM?
Authenticated encryption (prevents tampering)
Hardware acceleration in modern CPUs
Widely supported in Web Crypto API
Industry standard for data encryption
2. Storing Keys Locally in IndexedDB
Keys must persist across browser sessions but never leave the device:
typescript
interface StoredKey {
id: string; // Unique identifier
key: JsonWebKey; // Exported key in JWK format
createdAt: number; // Timestamp
fileIds: string[]; // Associated encrypted files
label?: string; // User-friendly name
}
async storeKey(keyId: string, key: CryptoKey): Promise<void> {
// Export key to JWK format for storage
const exportedKey = await crypto.subtle.exportKey('jwk', key);
// Store in IndexedDB
await this.db.keys.put({
id: keyId,
key: exportedKey,
createdAt: Date.now(),
fileIds: []
});
}
async retrieveKey(keyId: string): Promise<CryptoKey | null> {
const stored = await this.db.keys.get(keyId);
if (!stored) return null;
// Import JWK back to CryptoKey
return await crypto.subtle.importKey(
'jwk',
stored.key,
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
);
}
IndexedDB Benefits:
Persists across sessions
Larger storage quota than localStorage
Asynchronous API (non-blocking)
Structured data storage
3. File Encryption Process
Here's the complete encryption flow with proper IV (Initialization Vector) handling:
typescript
async encryptFile(file: File, key: CryptoKey): Promise<EncryptedFile> {
// Read file as ArrayBuffer
const fileBuffer = await file.arrayBuffer();
// Generate random IV (12 bytes for GCM)
const iv = crypto.getRandomValues(new Uint8Array(12));
// Encrypt the file
const encryptedData = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: iv,
tagLength: 128 // Authentication tag length
},
key,
fileBuffer
);
// Combine IV + encrypted data for storage
const combined = new Uint8Array(iv.length + encryptedData.byteLength);
combined.set(iv, 0);
combined.set(new Uint8Array(encryptedData), iv.length);
return {
data: combined.buffer,
originalName: file.name,
originalSize: file.size,
mimeType: file.type
};
}
Critical Security Details:
Unique IV per encryption: Never reuse IVs with the same key
IV prepended to ciphertext: Recipient needs IV to decrypt
Authentication tag: GCM includes integrity verification
No IV/key transmission: IV is public, key remains secret
4. Handling Large Files with Progress
Encrypting 50MB files can freeze the UI. Solution: chunk processing with progress tracking:
typescript
async encryptLargeFile(
file: File,
key: CryptoKey,
onProgress?: (percent: number) => void
): Promise<EncryptedFile> {
const chunkSize = 5 * 1024 * 1024; // 5MB chunks
const chunks: Uint8Array[] = [];
let offset = 0;
while (offset < file.size) {
const chunk = file.slice(offset, offset + chunkSize);
const buffer = await chunk.arrayBuffer();
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
buffer
);
// Store IV with each chunk
const combined = new Uint8Array(12 + encrypted.byteLength);
combined.set(iv);
combined.set(new Uint8Array(encrypted), 12);
chunks.push(combined);
offset += chunkSize;
// Report progress
if (onProgress) {
onProgress((offset / file.size) * 100);
}
}
// Combine all encrypted chunks
const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);
const result = new Uint8Array(totalLength);
let position = 0;
for (const chunk of chunks) {
result.set(chunk, position);
position += chunk.length;
}
return {
data: result.buffer,
originalName: file.name,
originalSize: file.size,
mimeType: file.type
};
}
5. Upload to Server
After client-side encryption, upload the blob:
typescript
async uploadEncryptedFile(
encrypted: EncryptedFile,
keyId: string
): Promise<UploadResult> {
const formData = new FormData();
formData.append('file', new Blob([encrypted.data]));
formData.append('metadata', JSON.stringify({
originalName: encrypted.originalName,
originalSize: encrypted.originalSize,
mimeType: encrypted.mimeType,
keyId: keyId // Key ID, NOT the key itself
}));
const response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
const result = await response.json();
return {
fileId: result.id,
url: result.url,
qrCode: result.qrCode
};
}
Server receives:
Encrypted blob (indecipherable)
Metadata (file name, size, type)
Key ID reference (NOT the actual key)
Server never receives:
Encryption key
Unencrypted file contents
Any way to decrypt the data
6. File Decryption Process
When someone downloads, the reverse happens:
typescript
async decryptFile(
encryptedData: ArrayBuffer,
key: CryptoKey
): Promise<File> {
const data = new Uint8Array(encryptedData);
// Extract IV (first 12 bytes)
const iv = data.slice(0, 12);
// Extract encrypted content (rest)
const encrypted = data.slice(12);
// Decrypt
const decrypted = await crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv: iv,
tagLength: 128
},
key,
encrypted
);
// Return as File object
return new File(
[decrypted],
metadata.originalName,
{ type: metadata.mimeType }
);
}
If decryption fails:
Wrong key provided
Data was tampered with (GCM auth tag fails)
Corrupted data
Folder Upload Support
One of FileBee's key features is preserving directory structure:
typescript
interface FolderStructure {
files: FileNode[];
totalSize: number;
fileCount: number;
}
interface FileNode {
path: string; // "project/src/components/App.tsx"
encryptedId: string; // Server-generated ID
size: number;
mimeType: string;
}
async uploadFolder(
files: File[],
key: CryptoKey,
onProgress?: (file: string, percent: number) => void
): Promise<FolderStructure> {
const structure: FolderStructure = {
files: [],
totalSize: 0,
fileCount: files.length
};
for (const file of files) {
// Get relative path (preserves folder structure)
const path = file.webkitRelativePath || file.name;
// Encrypt file
const encrypted = await this.encryptFile(file, key);
// Upload
const result = await this.uploadEncryptedFile(encrypted, keyId);
// Store in structure
structure.files.push({
path: path,
encryptedId: result.fileId,
size: file.size,
mimeType: file.type
});
structure.totalSize += file.size;
if (onProgress) {
onProgress(file.name, ((structure.files.length / files.length) * 100));
}
}
return structure;
}
Folder download reconstructs the directory tree:
typescript
async downloadFolder(
structure: FolderStructure,
key: CryptoKey
): Promise<void> {
const zip = new JSZip();
for (const node of structure.files) {
// Download encrypted file
const encrypted = await this.fetchFile(node.encryptedId);
// Decrypt
const decrypted = await this.decryptFile(encrypted, key);
// Add to zip with original path
zip.file(node.path, decrypted);
}
// Generate and download zip
const blob = await zip.generateAsync({ type: 'blob' });
saveAs(blob, 'filebee-folder.zip');
}
QR Code Generation
Every upload automatically generates a QR code for mobile sharing:
typescript
import QRCode from 'qrcode';
async generateShareQR(url: string, keyId: string): Promise<string> {
// Encode URL and key ID (NOT the key itself)
const shareData = {
url: url,
keyId: keyId,
service: 'FileBee'
};
const qrDataUrl = await QRCode.toDataURL(
JSON.stringify(shareData),
{
width: 400,
margin: 2,
color: {
dark: '#667eea', // FileBee brand color
light: '#ffffff'
},
errorCorrectionLevel: 'H' // High error correction
}
);
return qrDataUrl;
}
Security note: The QR code contains the URL and key ID reference, but not the encryption key itself. Users must share the key separately.
Storage Limits & Quota Management
FileBee implements fair usage limits:
50MB per file
250MB total storage per user
7-day automatic deletion
typescript
class QuotaManager {
private readonly MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
private readonly MAX_TOTAL_SIZE = 250 * 1024 * 1024; // 250MB
async checkQuota(userId: string, fileSize: number): Promise<QuotaCheck> {
// Check single file limit
if (fileSize > this.MAX_FILE_SIZE) {
return {
allowed: false,
reason: 'File exceeds 50MB limit',
currentUsage: 0,
limit: this.MAX_FILE_SIZE
};
}
// Check total usage
const userFiles = await this.getUserFiles(userId);
const currentUsage = userFiles.reduce((sum, f) => sum + f.size, 0);
if (currentUsage + fileSize > this.MAX_TOTAL_SIZE) {
return {
allowed: false,
reason: 'Total storage limit (250MB) exceeded',
currentUsage,
limit: this.MAX_TOTAL_SIZE
};
}
return {
allowed: true,
currentUsage,
limit: this.MAX_TOTAL_SIZE,
remaining: this.MAX_TOTAL_SIZE - currentUsage - fileSize
};
}
}
Automatic File Deletion
Privacy by design means temporary storage:
typescript
// Server-side cron job
class FileCleanupService {
private readonly RETENTION_DAYS = 7;
async cleanupExpiredFiles(): Promise<CleanupReport> {
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - this.RETENTION_DAYS);
const expiredFiles = await this.db.files
.where('uploadedAt')
.below(cutoffDate.getTime())
.toArray();
let deletedCount = 0;
let freedSpace = 0;
for (const file of expiredFiles) {
await this.storage.deleteFile(file.id);
await this.db.files.delete(file.id);
deletedCount++;
freedSpace += file.size;
}
return {
deletedCount,
freedSpace,
timestamp: Date.now()
};
}
}
// Run every hour
setInterval(() => {
cleanupService.cleanupExpiredFiles();
}, 60 * 60 * 1000);
Key Deletion = Data Destruction
This is a critical security feature:
typescript
async deleteEncryptionKey(keyId: string): Promise<DeletionResult> {
// Get key and associated files
const key = await this.db.keys.get(keyId);
if (!key) {
return { success: false, reason: 'Key not found' };
}
// Delete all files encrypted with this key from server
const deletionPromises = key.fileIds.map(fileId =>
this.api.deleteFile(fileId)
);
await Promise.all(deletionPromises);
// Delete key from local IndexedDB
await this.db.keys.delete(keyId);
return {
success: true,
filesDeleted: key.fileIds.length,
message: 'Key and all associated files permanently deleted'
};
}
Important: Once a key is deleted, the files are permanently inaccessible—even to FileBee administrators. This is not a bug; it's the core security guarantee.
Security Considerations
What FileBee Protects Against:
✅ Server-side data breaches: Attackers only get encrypted blobs
✅ Man-in-the-middle attacks: HTTPS + no key transmission
✅ Unauthorized access: Files useless without encryption key
✅ Government requests: Cannot decrypt what we don't have keys for
✅ Insider threats: Even developers cannot access user files
What Users Must Protect:
⚠️ Encryption keys: If lost, files cannot be recovered
⚠️ Key sharing: Share keys through secure, separate channels
⚠️ Browser security: Keys stored locally; compromised browser = compromised keys
Best Practices for Users:
Store keys securely (password manager recommended)
Share URL and key separately (different communication channels)
Never share keys over unsecured channels (unencrypted email, SMS)
Delete keys when files no longer needed (triggers file deletion)
Performance Optimizations
1. Web Workers for Heavy Encryption
typescript
// encryption.worker.ts
self.addEventListener('message', async (e: MessageEvent) => {
const { file, key } = e.data;
const encrypted = await encryptFile(file, key);
self.postMessage({
encrypted,
progress: 100
});
});
// Main thread
const worker = new Worker('./encryption.worker.ts', { type: 'module' });
worker.postMessage({ file, key });
worker.addEventListener('message', (e) => {
uploadEncryptedFile(e.data.encrypted);
});
2. Lazy Loading Components
typescript
// Only load when needed
const routes: Routes = [
{
path: 'upload',
loadChildren: () => import('./upload/upload.module')
.then(m => m.UploadModule)
},
{
path: 'download',
loadChildren: () => import('./download/download.module')
.then(m => m.DownloadModule)
}
];
3. Service Worker for Offline Support
typescript
// sw.js
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('filebee-v1').then((cache) => {
return cache.addAll([
'/',
'/styles.css',
'/main.js',
'/assets/logo.svg'
]);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
Testing Strategy
Unit Tests for Encryption
typescript
describe('EncryptionService', () => {
let service: EncryptionService;
beforeEach(() => {
service = new EncryptionService();
});
it('should encrypt and decrypt correctly', async () => {
const originalFile = new File(['test content'], 'test.txt');
const key = await service.generateKey();
const encrypted = await service.encryptFile(originalFile, key);
const decrypted = await service.decryptFile(encrypted.data, key);
expect(await decrypted.text()).toBe('test content');
});
it('should fail with wrong key', async () => {
const file = new File(['secret'], 'secret.txt');
const key1 = await service.generateKey();
const key2 = await service.generateKey();
const encrypted = await service.encryptFile(file, key1);
await expectAsync(
service.decryptFile(encrypted.data, key2)
).toBeRejected();
});
it('should handle large files', async () => {
const largeData = new Uint8Array(50 * 1024 * 1024); // 50MB
const file = new File([largeData], 'large.bin');
const key = await service.generateKey();
const encrypted = await service.encryptFile(file, key);
expect(encrypted.data.byteLength).toBeGreaterThan(0);
});
});
Integration Tests
typescript
describe('Upload-Download Flow', () => {
it('should complete full cycle', async () => {
const testFile = new File(['content'], 'test.txt');
// Upload
const uploadResult = await uploadService.upload(testFile);
expect(uploadResult.url).toBeTruthy();
// Download
const downloaded = await downloadService.download(
uploadResult.url,
uploadResult.keyId
);
expect(await downloaded.text()).toBe('content');
});
});
Lessons Learned
1. Browser Compatibility
Not all browsers support all Web Crypto features equally:
typescript
function checkBrowserSupport(): SupportCheck {
const support = {
crypto: !!window.crypto?.subtle,
indexedDB: !!window.indexedDB,
webWorkers: typeof Worker !== 'undefined',
fileAPI: !!(window.File && window.FileReader)
};
const allSupported = Object.values(support).every(v => v);
if (!allSupported) {
return {
supported: false,
missing: Object.entries(support)
.filter(([_, v]) => !v)
.map(([k]) => k)
};
}
return { supported: true };
}
2. IndexedDB Quirks
Always wrap IndexedDB operations in try-catch:
typescript
async safeDBOperation<T>(
operation: () => Promise<T>
): Promise<T | null> {
try {
return await operation();
} catch (error) {
if (error.name === 'QuotaExceededError') {
this.notifyUser('Storage quota exceeded');
} else if (error.name === 'InvalidStateError') {
this.notifyUser('Database in invalid state');
}
console.error('IndexedDB error:', error);
return null;
}
}
3. Mobile Safari Limitations
iOS Safari has aggressive storage limits:
typescript
async checkStorageEstimate(): Promise<void> {
if ('storage' in navigator && 'estimate' in navigator.storage) {
const { usage, quota } = await navigator.storage.estimate();
const percentUsed = (usage! / quota!) * 100;
if (percentUsed > 80) {
this.warnUser('Storage nearly full');
}
}
}
Future Enhancements
Planned features for FileBee:
Password-protected links - Additional encryption layer
Custom expiration times - User-defined deletion schedules
Download analytics - Track when files are accessed (privacy-respecting)
Progressive Web App - Full offline functionality
Encrypted chat - Discuss files securely with recipients
API access - Programmatic file sharing
Self-hosted option - Run your own FileBee instance
Key Takeaways
Building FileBee taught me that:
Zero-knowledge is viable with modern browser APIs
Security and UX can coexist with thoughtful design
Client-side encryption performs well even for large files
IndexedDB is production-ready for key management
Users value privacy when given secure options
Conclusion
FileBee proves that true privacy in file sharing is not just possible—it's practical. By leveraging the Web Crypto API and adopting a zero-knowledge architecture, we can build services that respect user privacy by design, not by policy.
The result is a platform where:
Files are encrypted before leaving your device
Keys never touch the server
Even the service provider cannot access your data
Privacy is guaranteed by cryptography, not trust
Try FileBee
Experience zero-knowledge file sharing at filebee.in
Features:
✅ 50MB per file, 250MB total storage
✅ End-to-end encryption with AES-256-GCM
✅ Local key management (IndexedDB)
✅ 7-day automatic deletion
✅ QR code generation for mobile sharing
✅ Folder uploads with preserved structure
✅ No registration required
✅ Completely free
Discussion
Questions I'd love to hear your thoughts on:
What other security features would you want?
Would you trust zero-knowledge architecture over traditional services?
How do you currently share sensitive files?
Interest in a self-hosted version?
Drop a comment below! I'm happy to discuss the technical implementation or answer questions about building secure web applications.
Connect:
- Website: https://filebee.in
Tags: #webdev #security #encryption #javascript #angular #privacy #zerotrust #cryptography
Comments
Join the discussionNo comments yet. Be the first to comment.