toPublicKeyDer method

Uint8List toPublicKeyDer()

Exports the public key as DER (SubjectPublicKeyInfo).

The binary counterpart of toPublicKeyPem, and what OpenSSL.loadPublicKeyDer reads back.

Implementation

Uint8List toPublicKeyDer() {
  final bindings = _context.bindings;

  // i2d with a null output asks for the length, then fills a buffer on the
  // second call — and advances the pointer it is given, which is why the
  // walking copy is kept separate from the one that gets freed.
  final length = bindings.i2d_PUBKEY(handle, nullptr);
  if (length <= 0) {
    throw OpenSslException('i2d_PUBKEY failed to size the public key');
  }

  final buffer = calloc<UnsignedChar>(length);
  final cursor = calloc<Pointer<UnsignedChar>>();
  try {
    cursor.value = buffer;
    final written = bindings.i2d_PUBKEY(handle, cursor);
    if (written != length) {
      throw OpenSslException('i2d_PUBKEY wrote $written of $length bytes');
    }
    return Uint8List.fromList(buffer.cast<Uint8>().asTypedList(length));
  } finally {
    calloc.free(buffer);
    calloc.free(cursor);
  }
}