Base64 in UE4

March 15, 2020, 1 p.m.

The base64 methods in UE4 don't work natively with cyrillic etc.


While I was looking for projects to contribute to on GitHub I remembered VaRest was on GitHub. I headed over to VaRest's repo and was looking at issues. I found the issue and so I went on my way of finding a solution.

 

My solution for encoding was to convert the input string to utf8 and then encode. My solution for decoding was practically the same, I convert the string to a tchar from utf8, decode, and then output the result. Pretty easy right? Yeah no this solution took me about an hour and I had to get some assistance from an acquaintance, because the encoding was adding extra chars on the end and some other random issues.

FString MyClass::Base64Encode(const FString& Source)
{
    TArray<uint8> ByteArray;
    FTCHARToUTF8 StringSrc = FTCHARToUTF8(Source.GetCharArray().GetData());
    ByteArray.Append((uint8*)StringSrc.Get(), StringSrc.Length());

    return FBase64::Encode(ByteArray);
}

// I don't know why I didn't change this method to just return the string like the encode string above...
bool MyClass::Base64Decode(const FString& Source, FString& Dest)
{
    TArray<uint8> ByteArray;
    bool Success = FBase64::Decode(Source, ByteArray);

    FUTF8ToTCHAR StringSrc = FUTF8ToTCHAR((const ANSICHAR*)ByteArray.GetData(), ByteArray.Num());
    Dest.AppendChars(StringSrc.Get(), StringSrc.Length() + 1);

    return Success;
}

 

until next time