Search code examples
phpsftplibssh2

PHP ssh2_auth_pubkey_file not working with encrypted private key


I am using ssh2 in PHP, as follows:

$connection = ssh2_connect($host, $port);
ssh2_auth_pubkey_file($connection, $username, $pubKey, $privKey, $passphrase);

This results in the error message:

ssh2_auth_pubkey_file(): Authentication failed for username using public key

I am however, able to connect fine by using sftp directly in a terminal.

$ sftp -oPort=PORT -i /path/to/private/key USER@HOST

(The sftp command responds to ask for the passphrase, and it then connects.)

I'm at a bit of a loss with debugging this - the ssh2 commands are asking for and being provided with all the relevant information to connect, and I can connect fine using sftp directly in a terminal. What might the problem be?


Solution

  • I ended up ditching ssh2 for phpseclib.

    First, load the private key as follows:

    $key = new Crypt_RSA();
    $key->setPassword($passphrase);
    $key->loadKey(file_get_contents($keyPath));
    

    Then login using the key:

    $sftp = new Net_SFTP($host, $port);
    $loginResult = $sftp->login($username, $key);