FromBase64String invalid length error

146 views Asked by At

I am currently creating a log-in system for a game. I am using ASP.NET MVC Web API 2 to get the data and pass it on to the database. The process is as follows:

  1. Username and other data is written to a WWWForm (Unity3d). Among this data, there is a protobuf-net serialized object passed on to a Convert.ToBase64String like this:

    using (MemoryStream ms = new MemoryStream())
    {
        Serializer.Serialize(ms, data);
        return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
    }
    

The data sent (in that particular field) is: CgkKAUMSAWMaAWMaACICIAoqAhAB

  1. The data sent is stored to a MS SQL Server database with column type varbinary after doing Convert.FromBase64String(). That looks like this: 0x0A090A01411201611A01611A002202200A2A021001

  2. The data is sent back (via HTTP Response) as Convert.ToBase64String().

That data looks exactly as before as sending it: CgkKAUMSAWMaAWMaACICIAoqAhAB

Upon receiving the data, this tries to de-serialize it:

using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(serverResponse)))
{
     return Serializer.Deserialize<User>(ms);
}

However, it fails on the Convert and tells me that the length is not valid, even though the length is 28. What am I doing wrong?

1

There are 1 answers

0
Camilo Terevinto On BEST ANSWER

Ooops, I found what was causing the error. Response came as this:

"CgkKAUMSAWMaAWMaACICIAoqAhAB"

I thought it was Unity showing me the response inside quotation marks, but the response actually had quotation marks. So this is the fix:

serverResponse = serverResponse.Replace("\"", "");

using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(serverResponse)))
{
     return Serializer.Deserialize<User>(ms);
}