How to encrypt user data in Firebase

NoNameProvided picture NoNameProvided · Jul 11, 2016 · Viewed 21.8k times · Source

I am using the email/password sign in method for Firebase. I would like to encrypt the data users save into the realtime database before sending it to the database. Firebase already handle the user password, but can I somehow use it to encrypt data which can't be decrypted by me only the client? It would be nice if I could achieve it with the client sdk.

So my flow would be something like this:

  1. User sign in with it's credentials (which is handled by firebase itself)
  2. User encrypt some data with some unique key, which can be generated only from the credentials or from some data available only for the user, but not me. (this key needs to be persistent between sessions, or after the user changed his password.)
  3. Data is saved into the database (I cant read it since its encrypted with the user credentials)
  4. User log in on a different device (the decryption key can be generated right away and data can be decrypted.)

Answer

Hollerweger picture Hollerweger · Jan 9, 2017

You can easily do that the following way:

  1. After user A logs in a random public private key pair is generated on his phone. eg.: use Ecc Curve25519
  2. The private key from A is stored securely on his phone
  3. The public key from A is stored in firebase and is accessible to anybody that chats with A.
  4. If X sends a message to A he fetches the public key from A from firebase encrypts the message for A locally and stores the encrypted message on firebase in the inbox from A
  5. A downloads the encrypted message from firebase and decrypts it with his private key stored on his phone

(vice versa for A to X)

If A want's to move to another phone or wants to use multiple phones you can do this that way:

  1. Ask A to define a strong password to encrypt his locally stored private key. (or create a random passphrase and use QR codes for key exchange)
  2. Encrypt the private key locally (eg.: use AES256) on his phone with the password from step 1 and upload it to firebase. (optional sign it with his private key)
  3. Download the encrypted private key from the second device from A
  4. Ask for the passphrase on the second device from A and store the private key securely (optional check the signature with the public key from A)
  5. Delete the encrypted private key from firebase if no backup is wanted