Skip to content

Instantly share code, notes, and snippets.

@gaibz
Last active May 5, 2021 07:34
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaibz/84a3148a278907da6072162ec8223c0b to your computer and use it in GitHub Desktop.
Save gaibz/84a3148a278907da6072162ec8223c0b to your computer and use it in GitHub Desktop.
NeDB Encryption & Decryption (Work 2020)
/**
* NeDB With Encryption & Decryption
* Last Update 12 Feb 2020
*
* @author : Herlangga Sefani Wijaya <https://github.com/gaibz>
*/
const path = require('path') // path for database
const Datastore = require("nedb") // of course you need NeDB
const crypto = require('crypto') // now is in node default module
let algorithm = 'aes-256-cbc' // you can choose many algorithm from supported openssl
let secret = 'superSecretKey'
let key = crypto.createHash('sha256').update(String(secret)).digest('base64').substr(0, 32)
const YOUR_SECRET_DB = new Datastore({
filename: path.join(db_path, "yourdatabasename.db"),
autoload: true,
afterSerialization(plaintext) {
const iv = crypto.randomBytes(16)
const aes = crypto.createCipheriv(algorithm, key, iv)
let ciphertext = aes.update(plaintext)
ciphertext = Buffer.concat([iv, ciphertext, aes.final()])
return ciphertext.toString('base64')
},
beforeDeserialization(ciphertext) {
const ciphertextBytes = Buffer.from(ciphertext, 'base64')
const iv = ciphertextBytes.slice(0, 16)
const data = ciphertextBytes.slice(16)
const aes = crypto.createDecipheriv(algorithm, key, iv)
let plaintextBytes = Buffer.from(aes.update(data))
plaintextBytes = Buffer.concat([plaintextBytes, aes.final()])
return plaintextBytes.toString()
},
})
@camhart
Copy link

camhart commented Dec 13, 2019

Is this guaranteed not to produce a \n?

@gaibz
Copy link
Author

gaibz commented Feb 6, 2020

Is this guaranteed not to produce a \n?

sorry I didn't watch this file anymore ..
but you can try .. i've use this method on my last project and there is no problem till now ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment