ALAppExtensions icon indicating copy to clipboard operation
ALAppExtensions copied to clipboard

[Implementation Question] CodeUnit: "Base64 Convert" - ValidLength / Padding

Open christianbraeunlich opened this issue 5 years ago • 3 comments

Dear Microsoft ALAppExtension-Developers,

with all due respect, may I ask this question:

Whenever I use the procedure FromBase64(Base64String: Text): Text procedure from the Base64Convert.Codeunit.al it returns me an InvalidLength-Error if the Length of the input text parameter is not a multiple of four.

Basically I have a JWToken and want to analyze the given payload. Therefore I have to decode the Base64 string value.

My current workaround is the following code:

    local procedure ConvertBase64ToValidLength(Base64: Text): Text
    var
        Base64Convert: Codeunit "Base64 Convert";
    begin
        if (StrLen(Base64) MOD 4) <> 0 then
            Base64 := Base64.Replace('=', '');

        if (StrLen(Base64) MOD 4) <> 0 then
            Base64 += '=';

        if (StrLen(Base64) MOD 4) <> 0 then
            Base64 += '=';

        exit(Base64Convert.FromBase64(Base64));
    end;

Am I doing something wrong? Could this be a fix so that I don't have to put this procedure/workaround in every single one of my AppExtensions?

Thanks in advance and have an otterly awesome day! 🦦

christianbraeunlich avatar Oct 06 '21 15:10 christianbraeunlich

Base64Convert.Codeunit.al uses the .NET implementation System.Convert.FromBase64String which requires the length of the base64 string to be a multiple of 4. Similarly, if you convert to a base64 string using the module, it uses System.Convert.ToBase64String which will pad the remaining bytes to ensure it's a multiple of 4.

EDIT: For your specific scenario, JWT uses Base64url, which uses a slightly different character set than Base64 and does not apply padding. The proper solution would be to use a Base64url decoder, for example: Base64UrlEncoder. We don't have any plans to include this as a system module, but you are welcome to contribute to the Base64 system module with a Base64UrlEncoder API.

stkillen avatar Oct 08 '21 08:10 stkillen

Thanks for reporting this. We agree, and we’ll publish a fix asap, either in an update for the current version or in the next major release. Please do not reply to this, as we do not monitor closed issues. If you have follow-up questions or requests, please create a new issue where you reference this one.

JesperSchulz avatar Oct 08 '21 14:10 JesperSchulz

I understand the confused emoji... The internal work item was resolved as "fixed" and hence the automation picked up that status and posted it to GitHub ;-) No changes are going to ship... Let me correct this issue. Sorry about the confusion.

JesperSchulz avatar Oct 25 '21 14:10 JesperSchulz