toPrivateKeyPem method

String toPrivateKeyPem({
  1. String? password,
})

Exports Private Key to PEM format.

If password is provided, utilizes PKCS#8 encryption (AES-256-CBC). Otherwise exports as unencrypted PKCS#8 or traditional format depending on Key Type.

Implementation

String toPrivateKeyPem({String? password}) {
  final bio = _context.createBio();
  Pointer<Uint8>? pw;
  Pointer<EVP_CIPHER> cipher = nullptr;
  int pwLen = 0;

  if (password != null) {
    final bytes = utf8.encode(password);
    pwLen = bytes.length;
    pw = _allocUtf8z(password);
    // PKCS#8 standard recommends AES-256-CBC
    cipher = _context.bindings.EVP_aes_256_cbc();
  }

  try {
    int result;
    if (password != null) {
       // Use PKCS#8 for encrypted keys (Standard)
       result = _context.bindings.PEM_write_bio_PKCS8PrivateKey(
          bio,
          handle,
          cipher,
          pw!.cast(), // char* kstr
          pwLen,      // klen - actual password length
          nullptr,
          nullptr
       );
    } else {
       result = _context.bindings.PEM_write_bio_PrivateKey(
          bio,
          handle,
          nullptr,
          nullptr,
          0,
          nullptr,
          nullptr
       );
    }

    if (result != 1) throw OpenSslException('Failed to write private key to PEM');
    return _context.bioToString(bio);
  } finally {
    if (pw != null) calloc.free(pw);
    _context.freeBio(bio);
  }
}