Last active
September 14, 2019 17:25
-
-
Save kennwhite/13962bc9856bfdad30a9f7b8ea8a100a to your computer and use it in GitHub Desktop.
Client Side Field Level Encryption Hello World for Node.js
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
// Simple Client-Side Field Level Encryption example for Node.js | |
// To install: mkdir proj; cp hello_fle_node.js proj; cd proj; npm install mongodb mongodb-client-encryption --save; node hello_fle_node.js | |
const dbName = 'demoFLE'; | |
const keyCollection = dbName + '.__keystore' | |
const dataCollection = 'people' | |
const url = "mongodb+srv://username:password@xxx.example.net/" + dbName; // 'mongodb://localhost' | |
const AWS_ACCESS_KEY = "AKIxxxxxxxxxxxxxxxxx" | |
const AWS_SECRET_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" | |
const AWS_MASTER_KMS_ARN = "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" | |
const LOCAL_MASTER_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" | |
const ENC_DETERM = 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' | |
const ENC_RANDOM = 'AEAD_AES_256_CBC_HMAC_SHA_512-Random' | |
// SEE: https://mongodb.github.io/node-mongodb-native/3.0/reference/ecmascriptnext/crud/#ecmascript-next-crud | |
const mongo = require('mongodb') | |
const MongoClient = require('mongodb').MongoClient; | |
const assert = require('assert'); | |
(async function() { | |
let client; | |
try { | |
client = await MongoClient.connect( | |
url, { | |
useNewUrlParser: true, | |
useUnifiedTopology: true, | |
monitorCommands: true, | |
autoEncryption: { | |
kmsProviders: { | |
aws: { | |
accessKeyId: AWS_ACCESS_KEY, | |
secretAccessKey: AWS_SECRET_KEY, | |
}, | |
local: { | |
key: Buffer.from( LOCAL_MASTER_KEY, "base64" ) | |
} | |
}, | |
keyVaultNamespace: keyCollection, | |
} | |
}) | |
console.log("Connected to server"); | |
console.log("Note: this example requires server-side json schema encryption specifiers.") | |
const db = client.db( dbName ); | |
// Get the collection | |
const col = db.collection( dataCollection ); | |
const document = { | |
"firstName": "Peter", | |
"lastName": "Parker", | |
"ssn": "901-01-1234", | |
} | |
// Insert a single document | |
const r = await col.insertOne( document ); | |
assert.equal(1, r.insertedCount); | |
// Get first two documents that match the query | |
const docs = await col.find().toArray(); | |
await console.log(docs) | |
} catch (err) { | |
console.log(err.stack); | |
} | |
// Close connection | |
client.close(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment