encodePemBlock function

String encodePemBlock(
  1. PemLabel label,
  2. List<int> data
)

Encode data as a PEM block with the given label.

Returns a textual string encoding data with label formatted following stricttextualmsg from RFC 7468.

Arbitrary data may be prepended to lines before a PEM block, and this package will ignore such data when parsing PEM blocks.

When encoding multiple PEM blocks, such a certificate chain, it is common to simply concatenate the PEM blocks. Towards this end the output of this function can be concatenated with other PEM blocks and parsed with decodePemBlocks.

Implementation

String encodePemBlock(PemLabel label, List<int> data) {
  final labels = _labels[label];
  if (labels == null) {
    throw AssertionError('Unkown label');
  }

  final s = StringBuffer();
  final L = labels.first;
  s.writeln('-----BEGIN $L-----');
  final lines = base64.encode(data);
  for (var i = 0; i < lines.length; i += 64) {
    s.writeln(lines.substring(i, math.min(lines.length, i + 64)));
  }
  s.writeln('-----END $L-----');
  return s.toString();
}