Uploading to an encrypted account
Writing to an encrypted account uses the same routes as any other account. The difference is that your code encrypts first, so the server only ever receives encrypted names and encrypted bytes. Files written this way open in every harbor0 app, just like files the apps encrypt themselves.
When to encrypt
Encrypt new names and new files when the account is encrypted and not being turned off:
const { user } = await api('GET', '/v1/users/me');
const encryptNew = !!user.e2ee && !user.e2ee.decryptingSince;While decryptingSince is set, the person's apps are decrypting everything back, so store new names and files unencrypted and leave out encrypted.
Send X-Harbor-E2EE: h0e1 on every file request, as on reads.
Folders, renames and moves
Wherever a route takes a name, send the encrypted name instead of the real one:
POST /v1/drive/folders
X-Harbor-E2EE: h0e1
{ "operationId": "…", "parentId": null, "name": "h0e1.B7r1nFttVaFQsM3mFgUm5BaBSKCnUpjrErbITFm8HVIX" }The same goes for PATCH /v1/drive/items/{id} (rename) and the optional name of a move. Because the same name always encrypts the same way, 409 NAME_CONFLICT works exactly as on other accounts.
Uploading a file
Follow Uploading files with these changes:
| Field | Value on an encrypted account |
|---|---|
name | The encrypted name. |
sizeBytes | The stored size: 80 + size + 16 × max(1, ceil(size / 4 MiB)). |
encrypted | true. |
mimeType | application/octet-stream, so the type stays hidden. |
contentHash | Leave it out when creating the upload. Send the SHA-256 of the stored bytes when completing it. |
The bytes you send in the parts are the stored bytes: the header, then each encrypted chunk, cut into parts of partSizeBytes like any other upload.
Encrypting the content
- Make a new random 32-byte content key, a random 8-byte nonce prefix and a random 12-byte wrap IV.
- Build bytes 0–19 of the header:
H0E1, the byte1, three zero bytes, the chunk size4194304as a big-endian 32-bit number, and the nonce prefix. - Encrypt the content key with AES-256-GCM, the file-wrapping key, the wrap IV and header bytes 0–19 as associated data. Bytes 20–31 of the header are the wrap IV, and bytes 32–79 are the result (32 bytes plus the 16-byte tag).
- Split the file into 4 MiB chunks (one empty chunk for an empty file) and encrypt each with the content key, exactly mirroring decryption: the nonce is the prefix plus the chunk number, and the associated data is header bytes 0–19 plus
1for the last chunk or0for the others. - The stored file is the 80-byte header followed by the encrypted chunks, in order.
import { createCipheriv, randomBytes } from 'node:crypto';
const CHUNK = 4 * 1024 * 1024;
function seal(key, iv, plain, aad) {
const c = createCipheriv('aes-256-gcm', key, iv);
c.setAAD(aad);
return Buffer.concat([c.update(plain), c.final(), c.getAuthTag()]);
}
/** The stored bytes for `plain`, with a new random content key. */
export function encryptFile(keys, plain) {
const header = Buffer.alloc(80);
header.write('H0E1', 0, 'latin1');
header[4] = 1;
header.writeUInt32BE(CHUNK, 8);
randomBytes(8).copy(header, 12);
const wrapIv = randomBytes(12);
wrapIv.copy(header, 20);
const bound = Buffer.from(header.subarray(0, 20));
const contentKey = randomBytes(32);
seal(keys.fileWrap, wrapIv, contentKey, bound).copy(header, 32);
const count = Math.max(1, Math.ceil(plain.length / CHUNK));
const out = [header];
for (let i = 0; i < count; i++) {
const nonce = Buffer.alloc(12);
header.copy(nonce, 0, 12, 20);
nonce.writeUInt32BE(i, 8);
const aad = Buffer.concat([bound, Buffer.from([i === count - 1 ? 1 : 0])]);
out.push(seal(contentKey, nonce, plain.subarray(i * CHUNK, (i + 1) * CHUNK), aad));
}
return Buffer.concat(out);
}import math, os, struct
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
CHUNK = 4 * 1024 * 1024
def encrypt_file(keys, plain: bytes) -> bytes:
"""The stored bytes for `plain`, with a new random content key."""
bound = b"H0E1" + bytes([1, 0, 0, 0]) + struct.pack(">I", CHUNK) + os.urandom(8)
content_key, wrap_iv = os.urandom(32), os.urandom(12)
header = bound + wrap_iv + AESGCM(keys.file_wrap).encrypt(wrap_iv, content_key, bound)
count = max(1, math.ceil(len(plain) / CHUNK))
out = [header]
for i in range(count):
nonce = bound[12:20] + struct.pack(">I", i)
aad = bound + (b"\x01" if i == count - 1 else b"\x00")
out.append(AESGCM(content_key).encrypt(nonce, plain[i * CHUNK:(i + 1) * CHUNK], aad))
return b"".join(out)Creating and completing the upload
const stored = encryptFile(keys, plain);
const contentHash = createHash('sha256').update(stored).digest('hex');
const { upload } = await api('POST', '/v1/uploads', {
operationId: randomUUID(),
parentId,
name: encryptName(keys, 'holiday.mp4'),
sizeBytes: stored.length,
encrypted: true,
mimeType: 'application/octet-stream',
});
// …send `stored` in parts of upload.partSizeBytes, as in "Uploading files"…
const { item } = await api('POST', `/v1/uploads/${upload.id}/complete`, { parts, contentHash });For a new version of an existing file, add driveItemId and baseRevision as usual, and encrypt with a new content key. Never reuse a header for different content.
Rules that keep files safe
- A new content key for every version. Each upload gets its own random content key, nonce prefix and wrap IV. Reusing them for different content would reuse AES-GCM nonces, which breaks the encryption.
- Retrying is fine. If an upload is interrupted, you can resend the same parts of the same stored bytes. Encrypting is deterministic for a given header, so re-encrypting a chunk with the same header gives the same bytes.
- Hash what you upload.
contentHashmust be the SHA-256 of the exact stored bytes, header included. harbor0 checks it, and the apps rely on it to tell whether their copy is current. - Keep names within 255 bytes. Longer names cannot be encrypted. The apps refuse them too.
- Times are visible.
modifiedAtandfileCreatedAtare stored as sent, unencrypted, like every item's other dates. Leave them out if they should stay private.
Check your work
Download the file again with your own client and compare it with the original, then open it in the harbor0 web app to be sure the apps read it too. The test vectors include a header (bigHeader) to encrypt a known 8,400,953-byte file with: your stored bytes must have the SHA-256 given in bigSha256.