1

I am trying to convert a byte[] to a Base64 string.

string output = Convert.ToBase64String(SQLDataHelper.EncryptAddValue(modifiedField.Value[nameof(RecordHistoryField.PreviousValue)]));

After plugging this output value into an online Base64 to Binary converter, I can see that it is not the correct value. It returns a list of random characters.

Note that the byte[] is showing the correct values ex: {94, 85, 60, ...} and when I convert it to a hex string, it gives me the binary that I am expecting, just with no 0x.

Edit:

Input: {94, 85, 60, 64, 62, 69, 77, 65, 131, 20, 125, 110, 136, 128, 87, 112}

Expected output: MHg1RTU1M0M0MDNFNDU0RDQxODMxNDdENkU4ODgwNTc3MA==

Actual output: XlU8QD5FTUGDFH1uiIBXcA==

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
gtighe
  • 21
  • 3

1 Answers1

2

The expected result is treating the 0x5E553C403E454D4183147D6E88805770 input as a string, instead of a binary value. We can match the expected result in C# by doing the same:

public static void Main()
{
    var b = new byte[] {94, 85, 60, 64, 62, 69, 77, 65, 131, 20, 125, 110, 136, 128, 87, 112};
    var c = "0x" + ByteArrayToString(b);
    Console.WriteLine(c);
    var result = Convert.ToBase64String(Encoding.UTF8.GetBytes(c));
    Console.WriteLine(result);
}

// Adapted from here: https://stackoverflow.com/a/311179/3043
public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:X2}", b);
  return hex.ToString();
}

See it here:

https://dotnetfiddle.net/YSlLJJ

Note the original C# in your question is still encoding all of the correct data. You can base-64 decode the XlU8QD5FTUGDFH1uiIBXcA== string to get back your original byte array. Anything different you see is something trying to treat that array as a string directly. And this is with much less storage space, CPU, and memory use. If possible, I'd stick with that, or if you need to match it to another system, fix that system (because it really is a bug there).

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794