Error converting Base64 to String

Asked

Viewed 2,592 times

1

I have a Base64 string but the C# compiler says it is not valid, I get the following error:

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

My code is this:

String s_data = "RmluYWwtUmVjaXBpZW50OiByZmM4MjI7IGd1YXJhbmFicmFzaWxAZ3VhcmFuYXN0b2NrLmNvbQ0KQWN0aW9uOiBmYWlsZWQNClN0YXR1czogNS4wLjANCkRpYWdub3N0aWMtQ29kZTogc210cDsgVGhlIGVtYWlsIGFjY291bnQgdGhhdCB5b3UgdHJpZWQgdG8gcmVhY2ggZG9lcyBub3QgZXhpc3QuIFBsZWFzZSB0cnkgZG91YmxlLWNoZWNraW5nIHRoZSByZWNpcGllbnQncyBlbWFpbCBhZGRyZXNzIGZvciB0eXBvcyBvciB1bm5lY2Vzc2FyeSBzcGFjZXMuIExlYXJuIG1vcmUgYXQgaHR0cHM6Ly9zdXBwb3J0Lmdvb2dsZS5jb20vbWFpbC8_cD1Ob1N1Y2hVc2VyIG40c29yMzk2MDY5M3dtaC4zNCAtIGdzbXRwDQpMYXN0LUF0dGVtcHQtRGF0ZTogV2VkLCAwNyBNYXIgMjAxOCAwOTo1MToxNiAtMDgwMCAoUFNUKQ0K";
byte[] data = Convert.FromBase64String(s_data);
string decodedString = Encoding.UTF8.GetString(data);

I tested the string of data on that website and there converts normally. I have converted other strings in base64 but this is giving problem.

1 answer

2


It happens because in converting to Base64 sometimes characters change from + and / for - and _

http://en.wikipedia.org/wiki/Base64#Implementations_and_history

Follows example working http://rextester.com/LJLLZO44181

String s_data = "RmluYWwtUmVjaXBpZW50OiByZmM4MjI7IGd1YXJhbmFicmFzaWxAZ3VhcmFuYXN0b2NrLmNvbQ0KQWN0aW9uOiBmYWlsZWQNClN0YXR1czogNS4wLjANCkRpYWdub3N0aWMtQ29kZTogc210cDsgVGhlIGVtYWlsIGFjY291bnQgdGhhdCB5b3UgdHJpZWQgdG8gcmVhY2ggZG9lcyBub3QgZXhpc3QuIFBsZWFzZSB0cnkgZG91YmxlLWNoZWNraW5nIHRoZSByZWNpcGllbnQncyBlbWFpbCBhZGRyZXNzIGZvciB0eXBvcyBvciB1bm5lY2Vzc2FyeSBzcGFjZXMuIExlYXJuIG1vcmUgYXQgaHR0cHM6Ly9zdXBwb3J0Lmdvb2dsZS5jb20vbWFpbC8_cD1Ob1N1Y2hVc2VyIG40c29yMzk2MDY5M3dtaC4zNCAtIGdzbXRwDQpMYXN0LUF0dGVtcHQtRGF0ZTogV2VkLCAwNyBNYXIgMjAxOCAwOTo1MToxNiAtMDgwMCAoUFNUKQ0K";
string converted = s_data.Replace('-', '+');
converted = converted.Replace('_', '/');
byte[] data = Convert.FromBase64String(converted);
string decodedString = Encoding.UTF8.GetString(data);
  • 1

    Thanks, I realized that I made this change when I was going to encode, but I didn’t when I was going to decode. It worked obg

Browser other questions tagged

You are not signed in. Login or sign up in order to post.