Skip to content

Instantly share code, notes, and snippets.

@DmitryLukyanov
Created August 17, 2022 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DmitryLukyanov/b8fd4006928cc4501c9115e476337102 to your computer and use it in GitHub Desktop.
Save DmitryLukyanov/b8fd4006928cc4501c9115e476337102 to your computer and use it in GitHub Desktop.
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Encryption;
using System;
using System.Collections.Generic;
using System.Threading;
namespace ConsoleApp23
{
class Program
{
private static CollectionNamespace collNamespace = CollectionNamespace.FromFullName("db.coll");
private static CollectionNamespace keyVaultNamespace = CollectionNamespace.FromFullName("db.__key");
static string GetKeyId()
{
var keyVaultMongoClient = new MongoClient();
var clientEncryptionSettings = new ClientEncryptionOptions(
keyVaultMongoClient,
keyVaultNamespace,
GetLocalKmsProvider());
var clientEncryption = new ClientEncryption(clientEncryptionSettings);
var dataKeyId = clientEncryption.CreateDataKey("local", new DataKeyOptions(), CancellationToken.None);
var base64DataKeyId = Convert.ToBase64String(GuidConverter.ToBytes(dataKeyId, GuidRepresentation.Standard));
clientEncryption.Dispose();
return base64DataKeyId;
}
static Dictionary<string, IReadOnlyDictionary<string, object>> GetLocalKmsProvider()
{
const string LocalMasterKey = "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk";
var localMasterKey = Convert.FromBase64String(LocalMasterKey);
var kmsProviders = new Dictionary<string, IReadOnlyDictionary<string, object>>();
var localKey = new Dictionary<string, object>
{
{ "key", localMasterKey }
};
kmsProviders.Add("local", localKey);
return kmsProviders;
}
private static BsonDocument CreateEncryptedMetadata(string dataEncriptionKeyBase64)
{
var keyId = new BsonBinaryData(Convert.FromBase64String(dataEncriptionKeyBase64), BsonBinarySubType.UuidStandard);
return new BsonDocument(nameof(keyId), new BsonArray(new[] { keyId }));
}
static void Main(string[] args)
{
#pragma warning disable CS0618 // Type or member is obsolete
BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;
#pragma warning restore CS0618 // Type or member is obsolete
var base64DataKeyId = GetKeyId();
var schemaMap = $@"{{
encryptMetadata: {CreateEncryptedMetadata(base64DataKeyId)},
properties: {{
name: {{
encrypt: {{
bsonType: 'string',
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
}}
}},
motherName: {{
encrypt: {{
bsonType: 'string',
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
}}
}}
}},
'bsonType': 'object'
}}";
var autoEncryptionSettings = new AutoEncryptionOptions(
keyVaultNamespace,
kmsProviders: GetLocalKmsProvider(),
schemaMap: new Dictionary<string, BsonDocument>() { { collNamespace.ToString(), BsonDocument.Parse(schemaMap) } });
var client = new MongoClient(new MongoClientSettings { AutoEncryptionOptions = autoEncryptionSettings });
var db = client.GetDatabase(collNamespace.DatabaseNamespace.DatabaseName);
var coll = db.GetCollection<BsonDocument>(collNamespace.CollectionName);
db.DropCollection(collNamespace.CollectionName);
var foo = new BsonDocument
{
{ "name", "Name" },
{ "motherName", "MotherName" },
{
"bars",
new BsonArray
{
new BsonDocument { { "name", "SuperA" }, { "createdAt", DateTime.Now } },
new BsonDocument { { "name", "SuperB" }, { "createdAt", DateTime.Now } }
}
}
};
coll.InsertOne(foo);
var result = coll.Find("{ 'bars' : { '$elemMatch' : { 'name' : 'SuperA' } } }").ToList();
// result is empty
// filter:
//{
// "find": "coll",
// "filter": {
// "bars": {
// "$elemMatch": {
// "name": {
// "$eq": new BinData(6, "Ae9X7o9YNECbvuFESnN/otgC6CXrGKtNCQE6XpSb0BxXduQDqtmr+AfN7SJunVop06o0eHuigU/YWU6j/JXfjYBv7erNLc+kR55a5mxarNmrbQ==")
// }
// }
// }
// },
// "lsid": {
// "id": UUID("8e5101d3-783a-4241-afb6-c6c4f8d4b47b")
// },
// "$clusterTime": {
// "clusterTime": Timestamp(1660701464, 2),
// "signature": {
// "hash": new BinData(0, "AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
// "keyId": NumberLong(0)
// }
// },
// "$db": "db"
//}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment