$ npm install encryption-encodingVersioned encryption encoding using hyperschema.
npm install encryption-encoding
const sodium = require('sodium-universal')
const b4a = require('b4a')
const { encrypt, decrypt } = require('encryption-encoding')
const password = b4a.alloc(32)
// ... fill password
const encrypted = await encrypt(plaintext, async (value) => {
const buffer = b4a.allocUnsafe(
value.byteLength + sodium.crypto_secretbox_MACBYTES + sodium.crypto_secretbox_NONCEBYTES
)
const nonce = buffer.subarray(0, sodium.crypto_secretbox_NONCEBYTES)
const box = buffer.subarray(nonce.byteLength)
sodium.randombytes_buf(nonce)
sodium.crypto_secretbox_easy(box, value, nonce, password)
return { value: buffer, version: 1 }
})
const decrypted = await decrypt(encrypted, async ({ value, version }) => {
const nonce = value.subarray(0, sodium.crypto_secretbox_NONCEBYTES)
const box = value.subarray(nonce.byteLength)
const output = b4a.allocUnsafe(box.byteLength - sodium.crypto_secretbox_MACBYTES)
sodium.crypto_secretbox_open_easy(output, box, nonce, password)
return output
})
await encrypt(data, callback)Calls callback(data) which should return { value, version }, then encodes the result using hyperschema.
await decrypt(buffer, callback)Decodes the buffer to { version, value }, passes it to callback, and returns the result.
Apache-2.0