Last active
December 24, 2020 08:56
-
-
Save karan9/33718dcfc22d023650928ce2c7d3fe69 to your computer and use it in GitHub Desktop.
This file contains 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
const { ClientEncryption } = require('mongodb-client-encryption'); | |
const base64 = require('uuid-base64'); | |
const mongoose = require('mongoose'); | |
// DONOT USE IN PRODUCTION | |
function getEncryptionKey() { | |
const arr = []; | |
for (let i = 0; i < 96; ++i) { | |
arr.push(i); | |
} | |
const key = Buffer.from(arr); | |
return key; | |
} | |
const key = getEncryptionKey(); | |
const keyVaultNamespace = 'client.encryption'; | |
const kmsProviders = { local: { key } }; | |
async function main() { | |
await mongoose.connect('ATLAS_URL', { | |
useNewUrlParser: true, | |
useUnifiedTopology: true, | |
// Configure auto encryption | |
autoEncryption: { | |
keyVaultNamespace, | |
kmsProviders | |
} | |
}); | |
const encryption = new ClientEncryption(mongoose.connection.client, { | |
keyVaultNamespace, | |
kmsProviders, | |
}); | |
const __key__ = await encryption.createDataKey('local'); | |
await mongoose.connection.dropCollection('karans').catch(() => {}); | |
await mongoose.connection.createCollection('karans', { | |
validator: { | |
$jsonSchema: { | |
bsonType: 'object', | |
properties: { | |
name: { | |
encrypt: { | |
bsonType: 'string', | |
keyId: [__key__], | |
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' } | |
} | |
} | |
} | |
} | |
}); | |
const Model = mongoose.model('Karan', mongoose.Schema({ name: String })); | |
await Model.create({ name: 'Karan Srivastava' }); | |
} | |
main().catch(console.log) |
This file contains 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
{ | |
"name": "fle-mongoose", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "Karan", | |
"license": "MIT", | |
"dependencies": { | |
"express": "^4.17.1", | |
"mongodb": "^3.6.3", | |
"mongodb-client-encryption": "^1.1.0", | |
"mongoose": "^5.11.8", | |
"uuid-base64": "^1.0.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment