Skip to content

Instantly share code, notes, and snippets.

@AcidLeroy
Created January 11, 2019 00:02
Show Gist options
  • Save AcidLeroy/68d80a4aedacea1451471c318e3ecc0b to your computer and use it in GitHub Desktop.
Save AcidLeroy/68d80a4aedacea1451471c318e3ecc0b to your computer and use it in GitHub Desktop.
This demonstrates how you can encrypt data using libsodium-wrappers for the Nedb NoSQL database. The algorithm is xchacha20poly1305
import { generateKey, encryptDocument, decryptDocument, ready } from 'easy-doc-crypt'
import Datastore = require('nedb')
(async function() {
await ready()
const key = generateKey('MyPassword123')
function encrypt(serialized :string) {
console.log('encrypt')
let d = encryptDocument(key.secret, serialized)
let s = JSON.stringify(d)
console.log('s = ', s)
return JSON.stringify(d)
}
function decrypt(serialized:string ){
console.log('decrypt')
let d = JSON.parse(serialized)
let result = decryptDocument(key.secret, d.header, d.cipherText)
console.log('decrypt result = ', result)
return result
}
let db = new Datastore({
filename: 'mydb',
autoload: true,
afterSerialization: encrypt,
beforeDeserialization: decrypt
})
let data = { firstName: 'Homer', lastName: 'Simpson' }
function getDocument(doc: any) {
db.findOne({ _id: doc._id }, function(err, doc) {
if (err) {
console.log('There was an error fetch doc: ')
} else {
console.log('retrieved doc: ', doc)
}
})
}
db.insert(data, function(err, doc) {
if (err) {
console.log('There was an error: ', err)
} else {
console.log('Inserted a doc: ', doc)
getDocument(doc)
}
})
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment