getPrivateKeys method

List<SSHKeyPair> getPrivateKeys([
  1. String? passphrase
])

Implementation

List<SSHKeyPair> getPrivateKeys([String? passphrase]) {
  late Uint8List unencryptedKeys;

  if (isEncrypted) {
    if (passphrase == null) {
      throw SSHKeyDecryptError('Private key is encrypted');
    }
    final passphraseBytes = Utf8Encoder().convert(passphrase);
    unencryptedKeys = _decryptPrivateKeyBlob(privateKeyBlob, passphraseBytes);
  } else {
    if (passphrase != null) {
      throw ArgumentError('Passphrase is not required for unencrypted keys');
    }
    unencryptedKeys = privateKeyBlob;
  }

  final reader = SSHMessageReader(unencryptedKeys);
  final checkInt1 = reader.readUint32();
  final checkInt2 = reader.readUint32();
  if (checkInt1 != checkInt2) {
    if (isEncrypted) {
      throw SSHKeyDecryptError('Invalid passphrase');
    } else {
      throw SSHKeyDecryptError('Invalid private key');
    }
  }

  final keypairs = <SSHKeyPair>[];
  for (var i = 0; i < publicKeys.length; i++) {
    final type = reader.readUtf8();
    switch (type) {
      case 'ssh-rsa':
        keypairs.add(OpenSSHRsaKeyPair.readFrom(reader));
        break;
      case 'ssh-ed25519':
        keypairs.add(OpenSSHEd25519KeyPair.readFrom(reader));
        break;
      case 'ecdsa-sha2-nistp256':
      case 'ecdsa-sha2-nistp384':
      case 'ecdsa-sha2-nistp521':
        keypairs.add(OpenSSHEcdsaKeyPair.readFrom(reader));
        break;
      default:
        throw UnsupportedError('Unsupported key type: $type');
    }
  }

  return keypairs;
}