Base64 and hex encoding

suggest change

Binary data such as images, hashes, keys and encrypted bytes often has to travel through channels that only handle text: JSON documents, HTTP headers, URLs, environment variables, config files and logs. Two encodings cover most of these cases:

In Dart, Base64 is built into dart:convert. Hex encoding is a few lines of code, or you can use hex from the convert package maintained by the Dart team.

Base64 encoding and decoding

Base64 works on bytes, not strings. To encode text, first convert it to bytes with utf8.encode(), then encode the bytes with base64.encode(). Decoding reverses both steps:

import 'dart:convert';

void main() {
  const text = 'Hello, Dart! 👋';

  final bytes = utf8.encode(text); // Uint8List of 17 bytes
  final encoded = base64.encode(bytes);
  print(encoded); // SGVsbG8sIERhcnQhIPCfkYs=

  final decodedBytes = base64.decode(encoded); // Uint8List
  final decoded = utf8.decode(decodedBytes);
  print(decoded); // Hello, Dart! 👋
  print(decoded == text); // true

  // Top-level shortcuts for the same operations.
  print(base64Encode(bytes) == encoded); // true
  print(utf8.decode(base64Decode(encoded))); // Hello, Dart! 👋
}

base64 is a constant instance of Base64Codec. base64Encode() and base64Decode() are top-level functions that do the same thing. Both utf8.encode() and base64.decode() return a Uint8List, which is the efficient type for byte data in Dart.

Don't skip the UTF-8 step. Code such as base64.encode(text.codeUnits) only works for ASCII text. For characters outside Latin-1 it produces wrong results or throws, because Dart strings are made of UTF-16 code units, not bytes.

Padding

Base64 encodes input in groups of 3 bytes. When the input length isn't a multiple of 3, the output is padded with = so its length is always a multiple of 4:

import 'dart:convert';

void main() {
  for (final s in ['a', 'ab', 'abc', 'abcd', 'abcde']) {
    print('${s.padRight(5)} -> ${base64.encode(utf8.encode(s))}');
  }
}

Output:

a     -> YQ==
ab    -> YWI=
abc   -> YWJj
abcd  -> YWJjZA==
abcde -> YWJjZGU=

You can compute the encoded size in advance: it's 4 * ((n + 2) ~/ 3) characters for n bytes. For example, 1,000,000 bytes become 1,333,336 characters.

Using fused codecs

utf8 is a Codec<String, List<int>> and base64 is a Codec<List<int>, String>. You can join them with fuse() into one Codec<String, String> that converts text straight to Base64 and back:

import 'dart:convert';

final utf8Base64 = utf8.fuse(base64);

void main() {
  final encoded = utf8Base64.encode('Grüße');
  print(encoded); // R3LDvMOfZQ==
  print(utf8Base64.decode(encoded)); // Grüße
}

URL-safe Base64

Standard Base64 uses + and /, which have special meaning in URLs and file names. The URL-safe variant (often called Base64URL) uses - and _ instead. Use base64Url to produce it:

import 'dart:convert';

void main() {
  final bytes = [0xfb, 0xff, 0xbf];

  print(base64.encode(bytes)); // +/+/
  print(base64Url.encode(bytes)); // -_-_

  // Dart's decoder accepts both alphabets.
  print(base64.decode('-_-_')); // [251, 255, 191]
  print(base64Url.decode('+/+/')); // [251, 255, 191]
}

base64Url.encode() keeps the = padding. Some formats, such as JWTs and many random token schemes, remove it. Dart's decoder, however, requires correct padding and throws a FormatException without it. Use normalize() to add the missing padding before decoding:

import 'dart:convert';
import 'dart:typed_data';

String encodeNoPadding(List<int> bytes) =>
    base64Url.encode(bytes).replaceAll('=', '');

Uint8List decodeNoPadding(String encoded) =>
    base64Url.decode(base64Url.normalize(encoded));

void main() {
  final bytes = [250, 251, 252, 253, 254, 255, 63, 62];

  final token = encodeNoPadding(bytes);
  print(token); // -vv8_f7_Pz4
  print(decodeNoPadding(token)); // [250, 251, 252, 253, 254, 255, 63, 62]

  try {
    base64Url.decode(token); // no padding
  } on FormatException catch (e) {
    print('FormatException: ${e.message}');
  }
}

normalize() also checks that the input contains only valid characters and converts it to the alphabet of the codec you call it on. If you prefer to add the padding by hand, use encoded.padRight((encoded.length + 3) ~/ 4 * 4, '=').

The JWT article uses unpadded Base64URL for token segments, and the Random numbers article uses base64Url to turn secure random bytes into tokens.

Handling invalid input

base64.decode() throws a FormatException when the input has an invalid character, a wrong length or wrong padding. Always handle this when the data comes from outside your program:

import 'dart:convert';
import 'dart:typed_data';

Uint8List? tryDecodeBase64(String input) {
  try {
    return base64.decode(input);
  } on FormatException {
    return null;
  }
}

void main() {
  print(tryDecodeBase64('YWJj')); // [97, 98, 99]
  print(tryDecodeBase64('YWJ')); // null (wrong length)
  print(tryDecodeBase64('YW*j')); // null (invalid character)
  print(tryDecodeBase64('YWJj\nZA==')); // null (whitespace isn't allowed)
}

Dart's decoder doesn't skip whitespace. Base64 from email (MIME) or PEM files is split into lines of 64 or 76 characters, so remove the whitespace before decoding. To produce such output, split the encoded string into lines yourself:

import 'dart:convert';

String wrapLines(String s, [int width = 64]) {
  final lines = <String>[];
  for (var i = 0; i < s.length; i += width) {
    lines.add(s.substring(i, i + width > s.length ? s.length : i + width));
  }
  return lines.join('\n');
}

void main() {
  final data = List<int>.generate(100, (i) => i);

  final pem = '-----BEGIN DATA-----\n'
      '${wrapLines(base64.encode(data))}\n'
      '-----END DATA-----';
  print(pem);

  // Decoding: drop the header lines and all whitespace.
  final body = pem
      .split('\n')
      .where((line) => !line.startsWith('-----'))
      .join()
      .replaceAll(RegExp(r'\s'), '');
  final decoded = base64.decode(body);
  print(decoded.length); // 100
}

Common uses of Base64

HTTP Basic authentication

The Authorization header for Basic authentication contains username:password encoded with standard Base64:

import 'dart:convert';

String basicAuth(String user, String password) =>
    'Basic ${base64.encode(utf8.encode('$user:$password'))}';

void main() {
  print(basicAuth('alice', 's3cret')); // Basic YWxpY2U6czNjcmV0
}

With the http package, pass it as a header: http.get(url, headers: {'Authorization': basicAuth(user, password)}). Base64 isn't encryption, so only send this over HTTPS. See HTTP Request for more about making requests.

Binary data in JSON

JSON has no binary type, so bytes are usually stored as Base64 strings:

import 'dart:convert';
import 'dart:typed_data';

class Attachment {
  final String name;
  final Uint8List content;

  Attachment(this.name, this.content);

  Map<String, dynamic> toJson() => {
        'name': name,
        'content': base64.encode(content),
      };

  factory Attachment.fromJson(Map<String, dynamic> json) => Attachment(
        json['name'] as String,
        base64.decode(json['content'] as String),
      );
}

void main() {
  final a = Attachment('hello.txt', utf8.encode('Hello, World!'));
  final json = jsonEncode(a);
  print(json); // {"name":"hello.txt","content":"SGVsbG8sIFdvcmxkIQ=="}

  final b = Attachment.fromJson(jsonDecode(json) as Map<String, dynamic>);
  print(utf8.decode(b.content)); // Hello, World!
}

See the JSON article for more about serialization.

Data URIs

A data URI embeds a file directly in a URL, for example an image in HTML or CSS. Dart's Uri class creates and parses them, including the Base64 part:

import 'dart:convert';

void main() {
  // The first 8 bytes of every PNG file.
  final pngSignature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];

  final uri = Uri.dataFromBytes(pngSignature, mimeType: 'image/png');
  print(uri); // data:image/png;base64,iVBORw0KGgo=

  final text = Uri.dataFromString('Hello, World!',
      mimeType: 'text/plain', encoding: utf8, base64: true);
  print(text); // data:;charset=utf-8;base64,SGVsbG8sIFdvcmxkIQ==
  // text/plain is the default MIME type, so it's left out.

  // Parsing a data URI.
  final data = Uri.parse(uri.toString()).data!;
  print(data.mimeType); // image/png
  print(data.isBase64); // true
  print(data.contentAsBytes()); // [137, 80, 78, 71, 13, 10, 26, 10]

  print(text.data!.contentAsString()); // Hello, World!
}

Encoding large files as a stream

base64.encoder and base64.decoder are Converters, so they can transform streams. This lets you encode or decode a large file in chunks without loading it all into memory. The converters keep their state between chunks, so chunk boundaries don't have to be multiples of 3 or 4:

import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  // Encode: bytes -> Base64 text -> ASCII bytes written to disk.
  await File('photo.jpg')
      .openRead()
      .transform(base64.encoder)
      .transform(ascii.encoder)
      .pipe(File('photo.jpg.b64').openWrite());

  // Decode: ASCII bytes -> Base64 text -> original bytes.
  await File('photo.jpg.b64')
      .openRead()
      .transform(ascii.decoder)
      .transform(base64.decoder)
      .pipe(File('photo-copy.jpg').openWrite());

  print(await File('photo.jpg').length() ==
      await File('photo-copy.jpg').length()); // true
}

Hex encoding

Writing your own

You don't need a package for hex. Convert each byte with toRadixString(16) and pad it to 2 digits. To decode, parse each pair of characters with int.parse(..., radix: 16):

import 'dart:typed_data';

final _hexDigits = RegExp(r'^[0-9a-fA-F]*$');

String toHex(List<int> bytes) {
  final sb = StringBuffer();
  for (final b in bytes) {
    sb.write((b & 0xff).toRadixString(16).padLeft(2, '0'));
  }
  return sb.toString();
}

Uint8List fromHex(String hex) {
  if (hex.length.isOdd || !_hexDigits.hasMatch(hex)) {
    throw FormatException('Invalid hex string', hex);
  }
  final result = Uint8List(hex.length ~/ 2);
  for (var i = 0; i < result.length; i++) {
    result[i] = int.parse(hex.substring(i * 2, i * 2 + 2), radix: 16);
  }
  return result;
}

void main() {
  final bytes = [0, 1, 15, 16, 127, 128, 255];

  final hex = toHex(bytes);
  print(hex); // 00010f107f80ff
  print(hex.toUpperCase()); // 00010F107F80FF
  print(fromHex(hex)); // [0, 1, 15, 16, 127, 128, 255]
  print(fromHex('DEADbeef')); // [222, 173, 190, 239]

  try {
    fromHex('abc');
  } on FormatException catch (e) {
    print('${e.message}: ${e.source}'); // Invalid hex string: abc
  }
}

Two details matter here:

Using package:convert

The convert package from the Dart team provides a hex codec with the same API as base64:

dependencies:
  convert: ^3.1.2
import 'package:convert/convert.dart';

void main() {
  final encoded = hex.encode([0xde, 0xad, 0xbe, 0xef]);
  print(encoded); // deadbeef

  print(hex.decode('DEADBEEF')); // [222, 173, 190, 239]

  try {
    hex.decode('abc'); // odd length
  } on FormatException catch (e) {
    print('Invalid: ${e.message}');
  }
}

hex.encode() produces lowercase output and hex.decode() accepts both cases. Like base64, hex.encoder and hex.decoder are converters you can use with Stream.transform().

Hashes and checksums

The crypto package returns a Digest. Its toString() gives the hex form, and its bytes property gives raw bytes you can encode in any format:

dependencies:
  crypto: ^3.0.6
import 'dart:convert';
import 'package:crypto/crypto.dart';

void main() {
  final digest = sha256.convert(utf8.encode('hello'));

  print(digest); // 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
  print(base64.encode(digest.bytes)); // LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=
  print(digest.bytes.length); // 32
}

The hex form has 64 characters and the Base64 form has 44. Use hex when people will read or compare the value (for example checksums for downloads), and Base64 when size matters (for example the Content-Digest HTTP header or Subresource Integrity attributes in HTML).

Integers in hex

For individual numbers, use toRadixString() and int.parse() with radix: 16. See Type conversion for other conversions:

void main() {
  print(255.toRadixString(16)); // ff
  print('0x${255.toRadixString(16).padLeft(4, '0')}'); // 0x00ff
  print(0xdeadbeef.toRadixString(16).toUpperCase()); // DEADBEEF

  print(int.parse('ff', radix: 16)); // 255
  print(int.parse('DEADBEEF', radix: 16)); // 3735928559
  print(int.tryParse('xyz', radix: 16)); // null

  // CSS-style color: #RRGGBB
  const color = 0x3366cc;
  final r = (color >> 16) & 0xff, g = (color >> 8) & 0xff, b = color & 0xff;
  print('$r, $g, $b'); // 51, 102, 204

  // Numbers larger than 64 bits need BigInt.
  print(BigInt.parse('ffffffffffffffffffff', radix: 16));
  // 1208925819614629174706175
}

Note that int.parse() doesn't accept a 0x prefix when you pass radix: 16. Strip it first, or call int.parse('0xff') without a radix, which understands the prefix.

A hex dump

When you debug binary protocols or file formats, a hex dump in the style of xxd or hexdump -C shows the bytes and their printable characters side by side:

import 'dart:convert';
import 'dart:math';

String hexDump(List<int> bytes) {
  final out = StringBuffer();
  for (var offset = 0; offset < bytes.length; offset += 16) {
    final row = bytes.sublist(offset, min(offset + 16, bytes.length));
    final hexPart =
        row.map((b) => b.toRadixString(16).padLeft(2, '0')).join(' ');
    final asciiPart = String.fromCharCodes(
        row.map((b) => b >= 0x20 && b < 0x7f ? b : 0x2e)); // 0x2e is '.'
    out.writeln('${offset.toRadixString(16).padLeft(8, '0')}  '
        '${hexPart.padRight(47)}  |$asciiPart|');
  }
  return out.toString();
}

void main() {
  print(hexDump(utf8.encode('Hello, Dart!\nBase64 & hex: é☕')).trimRight());
}

Output:

00000000  48 65 6c 6c 6f 2c 20 44 61 72 74 21 0a 42 61 73  |Hello, Dart!.Bas|
00000010  65 36 34 20 26 20 68 65 78 3a 20 c3 a9 e2 98 95  |e64 & hex: .....|

The last five bytes show how UTF-8 encodes é as 2 bytes (c3 a9) and ☕ as 3 bytes (e2 98 95).

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents