Last active
March 11, 2019 05:16
-
-
Save amarwadi/72e40954095f902d55b4ab7b9f61f183 to your computer and use it in GitHub Desktop.
Key Vault Encryption Serializer
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
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); | |
} |
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
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.