NetCordDev / NetCord

The modern and fully customizable C# Discord library.
https://netcord.dev
MIT License
65 stars 10 forks source link

Token fails to handle base64-encoded Id with missing padding #1

Closed wiesniak closed 2 years ago

wiesniak commented 2 years ago

Discord generates 3-part token, where first part is base64 encoded Id. This id is encoded without padding.

Token class fails when trying to obtain the Id and decode it if the token is missing padding (= at the end). This happens because Convert.FromBase64String method is strict and does not handle strings with missing padding.

Proposed change:

        var index = rawToken.IndexOf('.');
        var partial = rawToken[..index];

        var totalWidth = (int)Math.Ceiling((double)partial.Length / 4) * 4;
        partial = partial.PadRight(totalWidth, '=');

        var converted = Convert.FromBase64String(partial);
wiesniak commented 2 years ago

Option with modulo division

    private Snowflake EvaluateId(string token)
    {
        var index = token.IndexOf('.');
        var partial = token[..index];

        var lastSegmentLength = partial.Length % 4;

        var totalWidth = partial.Length + (lastSegmentLength == 0 ? 0 : 4 - lastSegmentLength);
        partial = partial.PadRight(totalWidth, '=');

        var converted = Convert.FromBase64String(partial);
        return new Snowflake(Encoding.ASCII.GetString(converted));
    }
KubaZ2 commented 2 years ago

It is fixed in v1.0.0-alpha.107.