50

I'm working with an API that requires data encoded in base64. How can I encode a simple string in base64?

Timothy Armstrong
  • 1,906
  • 2
  • 16
  • 19

2 Answers2

94

There is no need to use the crypto package since the core libraries provide built-in support for base64 encoding and decoding.

https://api.dartlang.org/stable/2.1.0/dart-convert/dart-convert-library.html

import 'dart:convert';

main() {
  final str = "Hello world";
  final bytes = utf8.encode(str);
  final base64Str = base64.encode(bytes);
  print(base64Str);
}
Ben Butterworth
  • 13,650
  • 4
  • 61
  • 95
Ben
  • 1,076
  • 1
  • 7
  • 5
  • 2
    It would be perfect to change UTF8 to utf8, and BASE64 to base64, and update the link to https://api.dartlang.org/stable/2.1.0/dart-convert/dart-convert-library.html – Chandler Jan 06 '19 at 09:16
26

It requires a few steps, but encoding a string in base64 is pretty straightforward.

Dart has a function in the package:crypto library, CryptoUtils.bytesToBase64, which takes a list of bytes to encode as base64. In order to get the list of bytes from a Dart string, you can use the UTF8.encode() function in the dart:convert library.

All together, this looks like:

import 'dart:convert';
import 'package:crypto/crypto.dart';

main() {
  var str = "Hello world";
  var bytes = UTF8.encode(str);
  var base64 = CryptoUtils.bytesToBase64(bytes);
  print(base64);
}

If you're working inside the browser, then you have the easier option of using the browser's built in btoa function. The above code snippet becomes:

import 'dart:html';

main() {
  var str = "Hello world";
  var base64 = window.btoa(str);
  print(base64);
}
Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506
Timothy Armstrong
  • 1,906
  • 2
  • 16
  • 19
  • 13
    As of 0.9.2 of the `crypto` package, `CryptoUtils` is deprecated. Use instead `BASE64` from the `dart:convert` package. – Günter Zöchbauer Apr 10 '16 at 12:27
  • Yes, this has been made much easier with BASE64 in dart:convert. Please consider marking Ben's answer as accepted instead of this one. – filiph Mar 03 '17 at 00:55