Cifrare i dati degli utenti
Con productKey la tua app cifra i dati di un utente nel browser, e il tuo server conserva solo dati cifrati. Né il tuo server, né una fuga del tuo database, né Novren ID possono leggerli.
Cifrare e decifrare un testo
const encoder = new TextEncoder()
const decoder = new TextDecoder()
/**
* `productKey` is the AES-GCM 256 key from completeLogin / embedLogin. `label` binds the
* ciphertext to its place (user + record), so it can't be moved to another record unnoticed.
*/
export async function encryptText(productKey: CryptoKey, text: string, label: string): Promise<string> {
const iv = crypto.getRandomValues(new Uint8Array(12)) // new for EVERY encryption
const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(label) }, productKey, encoder.encode(text))
const out = new Uint8Array(12 + sealed.byteLength)
out.set(iv)
out.set(new Uint8Array(sealed), 12)
return btoa(String.fromCharCode(...out))
}
export async function decryptText(productKey: CryptoKey, stored: string, label: string): Promise<string> {
const bytes = Uint8Array.from(atob(stored), (c) => c.charCodeAt(0))
const plain = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: bytes.subarray(0, 12), additionalData: encoder.encode(label) },
productKey,
bytes.subarray(12),
) // throws if the data or the label were changed
return decoder.decode(plain)
}
// Usage: the label names the user and the record.
// const body = await encryptText(login.productKey, note.text, `notes:${login.accountId}:${note.id}`)I commenti degli esempi sono in inglese, come il codice.
Le regole che contano
- Un IV nuovo a ogni cifratura. AES-GCM con la stessa chiave e lo stesso IV di 12 byte due volte rompe la riservatezza.
crypto.getRandomValuesa ogni chiamata, come sopra. - Lega il dato cifrato al suo posto con
additionalData(lalabel): utente, tipo di record, id del record. Un dato cifrato spostato su un altro record (per un bug o da qualcuno con accesso al tuo database) non si decifra. - Cifra prima della richiesta, decifra dopo la risposta. Il testo in chiaro esiste solo nel browser.
- Dai una versione al formato. Aggiungi un byte o un campo di versione accanto al dato cifrato, così potrai cambiare algoritmo o struttura più avanti.
File grandi
Per i file non cifrare tutto in una chiamata: dividi in pezzi (per esempio da 1 MiB), cifra ognuno con il suo IV e una label con l’indice del pezzo e un segno per l’ultimo, così i pezzi non si possono riordinare né troncare.
Ricerca e ordinamento
Il tuo server non può cercare né ordinare campi cifrati. Le scelte comuni: tenere in chiaro i metadati non sensibili (date, dimensioni), oppure cercare sul client dopo aver decifrato.
Condividere fra utenti
Per mandare dati a un altro utente della tua app, usa la sua identità pubblica dalla rubrica, controllata con verifyDirectoryEntry. Le funzioni per sigillare per un’identità (X-Wing) arrivano con i pacchetti pubblici; fino ad allora, scrivici se ti servono.
Quando la decifratura fallisce
crypto.subtle.decrypt lancia OperationError quando il dato cifrato è stato cambiato, la label è diversa, o la chiave è diversa. L’ultimo caso succede dopo un recupero dell’account via email, che crea chiavi nuove. Vedi La chiave dell’app.