local-first-web / state

A Redux-based state container for local-first software, offering seamless synchronization using Automerge CRDTs. (Formerly known as 🐟 Cevitxe).
187 stars 10 forks source link

Basic crypto library #68

Closed HerbCaudill closed 4 years ago

HerbCaudill commented 4 years ago

Starting to tackle the authorization & authentication scenarios described in #37 and #38 .

This PR introduces a library of crypto functions, along with tests, to support these scenarios. These functions aren't used anywhere besides tests yet. They currently live in the cevitxe package but may be moved to a cevitxe-crypto package.

symmetric // shared secret key

  encrypt(plaintext, password) => cipher
  decrypt(cipher, password) => plaintext

asymmetric // public/private keys

  keyPair() => {publicKey, secretKey}
  encrypt(plaintext, recipientPublicKey, senderSecretKey) => cipher
  decrypt(plaintext, senderPublicKey, recipientSecretKey) => plaintext

signatures

  keyPair() => {publicKey, secretKey}
  sign(content, secretKey) => signature
  verify({content, signature, publicKey}) => boolean

deriveKey(password) => key

These functions wrap the current best-in-class libraries as far as I've been able to determine - we're not rolling our own encryption.

New dependencies

I expected the javascript world to have a "standard" high-level library for encryption that works in Node.js as well as the browser. Turns out the landscape is still messy and confusing.

Node.js has a built-in crypto library, and a modern browser has an equivalent in the window.crypto.subtle library. I was able to find an isomorphic library that provides a common interface to both. But these are low-level libraries: the Web Crypto API explicitly warns developers against using it directly unless they know what they're doing:

There's a widely used high-level library called crypto-js, but this predates the Web Crypto API and does not inspire confidence.

I finally settled on the NaCl family of crypto APIs, all of which descend from a C library released in 2008 that was specifically designed not to expose footguns to developers.