Sample code for 30+ languages & platforms
React Native

Authenticate an SSH Tunnel with a Private Key

See more Socket/SSL/TLS Examples

Demonstrates Socket.SshAuthenticatePk, which authenticates an SSH tunnel session using a private key loaded into an SshKey object. Call SshOpenTunnel first.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The SSH server must have the corresponding public key authorized for the account. If the private key is encrypted, set the SshKey.Password property before loading it.

Chilkat React Native Downloads

React Native
import { Socket, SshKey } from '@chilkat/react-native'

async function chilkatExample() {
  const socket = new Socket();

  try {
    await socket.sshOpenTunnelAsync('ssh.example.com', 22);
  } catch {
    console.log(socket.lastErrorText);
    return;
  }

  // Load the SSH private key.  The file path is relative to the application's current working
  // directory.  If the key is encrypted, set the SshKey.Password property before calling
  // FromOpenSshPrivateKey.
  const sshKey = new SshKey();
  let keyText: string;
  try {
    keyText = sshKey.loadText('qa_data/id_ed25519');
  } catch {
    console.log(sshKey.lastErrorText);
    return;
  }

  try {
    sshKey.fromOpenSshPrivateKey(keyText);
  } catch {
    console.log(sshKey.lastErrorText);
    return;
  }

  // Authenticate the SSH tunnel session using public-key authentication.  The SSH server must have the
  // corresponding public key authorized for the account.
  try {
    await socket.sshAuthenticatePkAsync('sshUser', sshKey);
  } catch {
    console.log(socket.lastErrorText);
    return;
  }

  console.log('SSH public-key authentication succeeded.');
}