-3

I am very new to C#.

encodevalues(object)

I need to use above function where i have to encode the values of object. Object can be different every time like below

{ "name" "Swamy", "email": : "Swamy123@gmail.com }  
or
{"firstname": "Swamy", "lastname": "reddy"}
or 
{"name": "Swamy"}

So I want to encrypt the only values and return the object.

How can i do this, please help.

Best,

swamy
  • 49
  • 2
  • 10

1 Answers1

0

It seems like you want a function that encodes all string properties of any given object.

To do this, you can use a bit of reflection. Note however, that the function below performs the encoding in-place. If you need it to return an encoded copy of the original object, you'll need to do some cloning (which can get pretty complicated if you need deep cloning).

public static void EncodeAllProperties(object obj)
{
    var props = obj.GetType().GetProperties();

    foreach (var prop in props)
    {
        if (prop.PropertyType == typeof(string))
        {
            prop.SetValue(obj, Base64Encode(prop.GetValue(obj) as string));
        }
    }   
}

// From https://stackoverflow.com/a/11743162/11981207
public static string Base64Encode(string plainText)
{
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
    return System.Convert.ToBase64String(plainTextBytes);
}
Kei
  • 1,026
  • 8
  • 15