Last active
May 5, 2021 07:34
-
-
Save gaibz/84a3148a278907da6072162ec8223c0b to your computer and use it in GitHub Desktop.
NeDB Encryption & Decryption (Work 2020)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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() | |
}, | |
}) |
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
Is this guaranteed not to produce a \n?