Fail to convert base64 string when using TryFromBase64String

77 views Asked by At

I receive a Guid as a base64 string. By using the Convert.FromBase64String(b64), the conversion is working well, then I try to use the Convert.TryFromBase64String(b64) but in that case, the method return false and my byte array stays empty

var dataString = "kADs1tnSQ+2ehpdtUAK/Jg==";
// output: d6ec0090-d2d9-ed43-9e86-976d5002bf26
Console.WriteLine(new Guid(Convert.FromBase64String(dataString)));

Span<byte> bytes = new();
bool success = Convert.TryFromBase64String(dataString, bytes, out int _);

// output: False, then FormatException
Console.WriteLine(success);
Console.WriteLine(new Guid(success ? bytes : Convert.FromHexString(dataString)));

I guess my problem is with the initialization of the Span, because if I use new byte[16], it is working, but is it safe to write it using a fixed size of 16?

2

There are 2 answers

0
Dmitry Bychenko On BEST ANSWER

You should provide bytes with allocated space, e.g.

// 16 bytes to store parsed GUID
byte[] bytes = new byte[16];

bool success = Convert.TryFromBase64String(dataString, bytes, out int _);

Similar, if you want to use Span:

// Span of the array which allocates 16 bytes to store GUID
var bytes = new byte[16].AsSpan();

bool success = Convert.TryFromBase64String(dataString, bytes, out int _);
0
Guru Stron On

You need to initialize Span and allocate space to write the processed result. For example:

Span<byte> bytes = stackalloc byte[16];
bool success = Convert.TryFromBase64String(dataString, bytes, out int bytesWritten);

Otherwise you are creating an empty one and Convert.TryFromBase64String will write zero bytes into it (it can't and won't allocate any space for the passed one).

From the Convert.TryFromBase64String docs (emphasis mine):

bytes Span<Byte>
The span in which to write the converted 8-bit unsigned integers. When this method returns false, either the span remains unmodified or contains an incomplete conversion of s, up to the last valid character.

So you will get success as False on actually valid base64 string which you will then try to process as a hex one.