Search code examples
c#base64bytesystemencode

String value system.byte[] while coverting Base64 value to string in c#


I have two LDIF files from where I am reading values and using it for comparsion using c# One of the attribute: value in LDIF is a base64 value, need to convert it in UTF-8 format

displayName:: Rmlyc3ROYW1lTGFzdE5hbWU=

So I thought of using string -> byte[], but I am not able to use the above displayName value as string

byte[] newbytes = Convert.FromBase64String(displayname);
string displaynamereadable = Encoding.UTF8.GetString(newbytes);

In my C# code, I am doing this to retrieve the values from the ldif file

for(Entry entry ldif.ReadEntry() ) //reads value from ldif for particular user's
{
    foreach(Attr attr in entry)   //here attr gives attributes of a particular user
    {
        if(attr.Name.Equals("displayName"))
        {
            string attVal = attr.Value[0].ToString();       //here the value of String attVal is system.Byte[], so not able to use it in the next line
            byte[] newbytes = Convert.FromBase64String(attVal);   //here it throws an error mentioned below 
            string displaynamereadable = Encoding.UTF8.GetString(attVal);
        }
    }
}

Error:

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

I am trying to user attVal as String so that I can get the encoded UTf-8 value but its throwing an error. I tried to use BinaryFormatter and MemoryStream as well, it worked but it inserted so many new chars with the original value.

Snapshot of BinaryFormatter:

object obj = attr.Value[0];
byte[] bytes = null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
   {
      bf.Serialize(ms, obj);
      bytes = (ms.ToArray());
   }
 string d = Encoding.UTF8.GetString(bytes);

So the result after encoding should be: "FirstNameLastName"

But it gives "\u0002 \u004 \u004 ...................FirstNameLastName\v"

Thanks,


Solution

  • Base64 was designed to send binary data through transfer channels that only support plain text, and as a result, Base64 is always ASCII text. So if attr.Value[0] is a byte array, just interpret those bytes as string using ASCII encoding:

    String attVal = Encoding.ASCII.GetString(attr.Value[0] as Byte[]);
    Byte[] newbytes = Convert.FromBase64String(attVal);
    String displaynamereadable = Encoding.UTF8.GetString(newbytes);
    

    Also note, your code above was feeding attVal into that final line rather than newbytes.