[CSHARP-2175] Can I access another field/property during Serialization? Created: 05/Feb/18  Updated: 27/Oct/23  Resolved: 01/Apr/19

Status: Closed
Project: C# Driver
Component/s: Serialization
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Anup Marwadi Assignee: Wan Bachtiar
Resolution: Works as Designed Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related

 Description   

Hello,
I have been trying to figure out the best approach to encrypt specified properties using attributes and a custom Serializer. I am trying to figure out if there's a way to get other properties of the document during serialization so that I can encrypt the data using a key that is setup in the object? The key is generated at runtime.

Here is a stack overflow link that has gone unanswered:
https://stackoverflow.com/questions/48512543/mongodb-serialization-c-sharp-adding-additional-encrypted-field-properties

I have also posted on the MongoDB Google group:
https://groups.google.com/forum/#!topic/mongodb-user/qpwn2X11OL0

Unless I'm mistaken, there's no possible way to accomplish this?

Thank you



 Comments   
Comment by Wan Bachtiar [ 19/Mar/19 ]

Unless I'm mistaken, there's no possible way to accomplish this?

Hi Anup,

You can do this by writing and registering a custom serializer for the class. Depending on your requirements and user case, you can even rewrite the entire document in the serialization, for example if you have a class:

public class Person {
    public ObjectId Id {get; set; }
    public string Email { get; set; }
    public string ContentEncryptionKey { get; protected set; }
}

You can write a custom serializer as below example:

class PersonSerializer : SerializerBase<Person>
{
    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Person value)
    {
        context.Writer.WriteStartDocument();
        context.Writer.WriteName("_id"); 
        context.Writer.WriteObjectId(value.Id);
        context.Writer.WriteName("ContentEncryptionKey");
        context.Writer.WriteString(value.ContentEncryptionKey);
        context.Writer.WriteName("Email");
        /* Perform your encryption logic here (below is just an example)*/
        context.Writer.WriteString(
                        Convert.ToBase64String(
                            Encoding.ASCII.GetBytes(
                                String.Concat(value.Email, value.ContentEncryptionKey)
                            )
                        )
                    );
        context.Writer.WriteEndDocument();
    }
    ...
}

Please note that the CSHARP project is for reporting bugs or feature suggestions for the MongoDB .NET/C# driver.

Regards,
Wan.

Generated at Wed Feb 07 21:41:48 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.