Search code examples
dartflutterbase64base64url

How to encode and decode Base64 and Base64Url in Flutter / Dart


I want to encode the following string in Base64Url in Flutter and decode it in on a Dart server.

"username:password"

How do I do that? And how do I do it in Base64?


Solution

  • The dart:convert library contains an encoder and decoder for Base64 and Base64Url. However, they encode and decode Lists of integers, so for strings you also need to encode and decode in UTF-8. Rather than doing these two encodings separately, you can combine them with fuse.

    You need to have the following import:

    import 'dart:convert';
    

    Base64

    String credentials = "username:password";
    Codec<String, String> stringToBase64 = utf8.fuse(base64);
    String encoded = stringToBase64.encode(credentials);      // dXNlcm5hbWU6cGFzc3dvcmQ=
    String decoded = stringToBase64.decode(encoded);          // username:password
    

    Note that this is equivalent to:

    String encoded = base64.encode(utf8.encode(credentials)); // dXNlcm5hbWU6cGFzc3dvcmQ=
    String decoded = utf8.decode(base64.decode(encoded));     // username:password
    

    Base64Url

    String credentials = "username:password";
    Codec<String, String> stringToBase64Url = utf8.fuse(base64Url);
    String encoded = stringToBase64Url.encode(credentials);      // dXNlcm5hbWU6cGFzc3dvcmQ=
    String decoded = stringToBase64Url.decode(encoded);          // username:password
    

    Again, this is equivalent to:

    String encoded = base64Url.encode(utf8.encode(credentials)); // dXNlcm5hbWU6cGFzc3dvcmQ=
    String decoded = utf8.decode(base64Url.decode(encoded));     // username:password
    

    Notes

    • Base64 is encoding, not compression. It won't make your string shorter.
    • Base64 is encoding, not encryption. Anyone can decode and read it. Don't send private data over an open network even if it is encoded in Base64.

    See also