Skip to content

Commit

Permalink
Encrypt, rather than hash, user email
Browse files Browse the repository at this point in the history
Hashing is no good for email storage because we actually need to be able
to use it! Therefore, we are now encrypting using a Node implementation
of libsodium. Currently we're storing the key in the ecosystem file,
which is clearly not ideal, we may need to think about passing it in
when starting the instance or similar.

- Use libsodium to encrypt and decrypt a user's email address
- Added scripts/create-sodium-key.js to create a sodium compliant key
  • Loading branch information
Andrew Isherwood committed Oct 30, 2020
1 parent 17d42c3 commit 2c48103
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 361 deletions.
40 changes: 40 additions & 0 deletions helpers/encryption.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const _sodium = require('libsodium-wrappers');

const encryption = {
encrypt: async (toEncrypt) => {
await _sodium.ready;
const sodium = _sodium;

// Get the key
const key = sodium.from_base64(process.env.KEY);

// Generate a nonce and the cipher text
const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);
const ciphertext = sodium.crypto_secretbox_easy(toEncrypt, nonce, key);

// Prepend the nonce to the cipher text, they're stored
// together
let merged = new Uint8Array(nonce.length + ciphertext.length);
merged.set(nonce);
merged.set(ciphertext, nonce.length);

return sodium.to_base64(merged);
},
decrypt: async (toDecryptWithNonce) => {
await _sodium.ready;
const sodium = _sodium;

const key = sodium.from_base64(process.env.KEY);
toDecryptWithNonce = sodium.from_base64(toDecryptWithNonce);

if (toDecryptWithNonce.length < sodium.crypto_secretbox_NONCEBYTES + sodium.crypto_secretbox_MACBYTES) {
throw 'Invalid cyphertext and/or nonce';
}

const nonce = toDecryptWithNonce.slice(0, sodium.crypto_secretbox_NONCEBYTES);
const ciphertext = toDecryptWithNonce.slice(sodium.crypto_secretbox_NONCEBYTES);
return sodium.crypto_secretbox_open_easy(ciphertext, nonce, key);
}
};

module.exports = encryption;
Loading

0 comments on commit 2c48103

Please sign in to comment.