Dart - Encode and decode base64 string

As of 0.9.2 of the crypto package

CryptoUtils is deprecated. Use the Base64 APIs in dart:convert and the hex APIs in the convert package instead.

import 'dart:convert' show utf8, base64;

main() {
  final str = 'https://dartpad.dartlang.org/';

  final encoded = base64.encode(UTF8.encode(str));
  print('base64: $encoded');

  final str2 = utf8.decode(base64.decode(encoded));
  print(str2);
  print(str == str2);
}

Try it in DartPad


I would comment on Günter's April 10th, 2016, post, but I don't have the reputation. As he says, you should use the dart:convert library, now. You have to combine a couple of codecs to get a utf8 string out of a base64 string and vice-versa. This article says that fusing your codecs is faster.

import 'dart:convert';

void main() {
  var base64 = 'QXdlc29tZSE=';
  var utf8 = 'Awesome!';

  // Combining the codecs
  print(utf8 == UTF8.decode(BASE64.decode(base64)));
  print(base64 == BASE64.encode(UTF8.encode(utf8)));
  // Output:
  // true
  // true

  // Fusing is faster, and you don't have to worry about reversing your codecs
  print(utf8 == UTF8.fuse(BASE64).decode(base64));
  print(base64 == UTF8.fuse(BASE64).encode(utf8));
  // Output:
  // true
  // true
}

https://dartpad.dartlang.org/5c0e1cfb6d1d640cdc902fe57a2a687d


You can use the BASE64 codec (renamed base64 in Dart 2) and the LATIN1 codec (renamed latin1 in Dart 2) from convert library.

var stringToEncode = 'Dart is awesome';

// encoding

var bytesInLatin1 = LATIN1.encode(stringToEncode);
// [68, 97, 114, 116, 32, 105, 115, 32, 97, 119, 101, 115, 111, 109, 101]

var base64encoded = BASE64.encode(bytesInLatin1);
// RGFydCBpcyBhd2Vzb21l

// decoding

var bytesInLatin1_decoded = BASE64.decode(base64encoded);
// [68, 97, 114, 116, 32, 105, 115, 32, 97, 119, 101, 115, 111, 109, 101]

var initialValue = LATIN1.decode(bytesInLatin1_decoded);
// Dart is awesome

If you always use LATIN1 to generate the encoded String you can avoid the 2 convert calls by creating a codec to directly convert a String to/from an encoded String.

var codec = LATIN1.fuse(BASE64);

print(codec.encode('Dart is awesome'));
// RGFydCBpcyBhd2Vzb21l

print(codec.decode('RGFydCBpcyBhd2Vzb21l'));
// Dart is awesome

Here is a example of encoding/decoding in dart:

main.dart:

import 'dart:convert';

main() {
  // encode
  var str = "Hello world";
  var bytes = utf8.encode(str);
  var base64Str = base64.encode(bytes);
  print(base64Str);

  // decode
  var decoded_bytes = base64.decode(base64Str);
  var decoded_str = utf8.decode(decoded_bytes);
  print(decoded_str);
}

Tags:

Dart