Skip to content

Instantly share code, notes, and snippets.

@amarwadi
Last active March 11, 2019 05:16
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 amarwadi/72e40954095f902d55b4ab7b9f61f183 to your computer and use it in GitHub Desktop.
Save amarwadi/72e40954095f902d55b4ab7b9f61f183 to your computer and use it in GitHub Desktop.
Key Vault Encryption Serializer
public class KeyVaultEncryptionSerializer : IBsonSerializer
{
private readonly string _elementName;
public KeyVaultEncryptionSerializer(string elementName)
{
_elementName = elementName;
}
public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
return context.Reader.ReadString();
}
public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
{
//I COULD POTENTIALLY WRITE A DOCUMENT FOR EVERY ENCRYPTED NODE
//context.Writer.WriteStartDocument();
//context.Writer.WriteName($"{_elementName}_Encrypted");
//context.Writer.WriteEndDocument();
//OR I COULD SIMPLY WRITE THE ENCRYTPED VALUE
var symmetricKey = "someKey"; //Here's where I need to read the document's CekProperty
var encryptedValue = EncryptData(value.ToString(), symmetricKey);
//encrypt the value using the Key obtained above. In this example, I'm simply appending the key
//for illustration purposes
context.Writer.WriteString(encryptedValue);
}
public Type ValueType => typeof(string);
}
@amarwadi
Copy link
Author

amarwadi commented Feb 8, 2018

My goal was to either create a new property {PropertyName}_Encrypted to store the encrypted value. Or use the same property and store the encrypted value. Irrespective of how the value is stored, the problem is that the current MongoDB C# driver provides no way of looking up any other property while serializing a given property. If there was a way for me to look at the Symmetric key and use it to encrypt the data, I'd be in business. The symmetric key would itself eventually be encrypted by Azure Key Vault Master Key (which is another attribute I would create). At that point, the process of asymmetric encryption would be complete w/o any additional ceremony. I would get away by purely using attributes for properties I need to encrypt, and a single IEncryptable interface that could allow me to encrypt any object that implemented it.

@joshbouganim
Copy link

did you ever get this to a working solution? currently in need for an encryption attribute. bonus points if it can support azure keyvault

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