Convert.FromBase64String does not work in code but works in online tool

URL Decoding will remove + from a base64 string making it invalid. There's no reason to down vote me for pointing it out. Others reading this question will use that code and it is flawed. If you decode 'a+==' the result will be the character 'k'. If you use URL Decoding to decode 'a+==' the URL decoding will turn the string into 'a ==' and you will get an exception trying to decode it.

In short, the .Net Framework is using a variant of Base64 encoding which does not allow invalid characters and PHP, used by the site in question, is using another variant which allows non-valid characters but discards them.

Base64 encoding converts three octets into four encoded characters. Valid characters for the first 62 of the 64 characters in Base64 encoding:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

There are several variants which allow different characters for characters 62 and 63. With C#, as with the most common variants, the full character set is:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=

https://msdn.microsoft.com/en-us/library/dhx0d524(v=vs.110).aspx

The base-64 digits in ascending order from zero are the uppercase characters "A" to "Z", the lowercase characters "a" to "z", the numerals "0" to "9", and the symbols "+" and "/". The valueless character, "=", is used for trailing padding.

This variant is known is the standard 'base64' encoding for RFC 3548 or RFC 4648 in which invalid values are forbidden unless otherwise specified.

PHP uses Base64 transfer encoding for MIME (RFC 2045) which allows non-valid characters but discards them.

In all other Base64 variants non-valid characters are forbidden.

If the original Base64 was actually supposed to contain the - character it is using a different variant.

See: https://en.wikipedia.org/wiki/Base64#Variants_summary_table


You'll have to remove the -- prefix from your string like was mentioned above. I want to add that I got the same error when I had data:image/jpeg;base64, prefix in my base64 string when using Convert.FromBase64String(str).

Removing data:image/jpeg;base64, from the string worked.


Your code is not a valid Base64 string. The - characters in the beginning of the string are invalid. You can convert it this way.

using System;
using System.Text;

var decodedString = "--W3sic3RhcnRfdGltZSI6IjAiLCJwcm9kdWN0X2lkIjoiODQwMDMzMDQiLCJ1cmwiOiIifSx7InN0YXJ0X3RpbWUiOiI3OSIsInByb2R1Y3RfaWQiOiI4NDAzNjk2MSIsInVybCI6IiJ9LHsic3RhcnRfdGltZSI6IjgyIiwicHJvZHVjdF9pZCI6Ijg0MDAzMDIwIiwidXJsIjoiIn0seyJzdGFydF90aW1lIjoiMTA5IiwicHJvZHVjdF9pZCI6IiIsInVybCI6Imh0dHBzOi8vYmxvZy5sYXJlaW5lZHVzaG9wcGluZy5jYS8yMDE3LzAxL3RyYW5zZm9ybWVyLXNlcy12aWV1eC1nYW50cy1kZS1jdWlyLWVuLTUtbWludXRlcy8ifV0="
    .Replace("-", "");
var bytes = Convert.FromBase64String(decodedString);
var encodedString = Encoding.UTF8.GetString(bytes);
Console.WriteLine(encodedString);

Tags:

C#

Base64