Search code examples
phpopensshphpseclib

Can not login using phpseclib with RSA keys?


I'm trying to use phpseclib to have an app executing remote commands on a linux server. I easily got it to work with username/password but I don't want to let that info in a plain text file so I want to use OpenSSH generated keys. Here is the buggy code.

<?php
include 'Crypt/RSA.php';
include 'Net/SSH2.php';

$key = new Crypt_RSA();
$key->loadKey('key');
echo file_get_contents('key');

$ssh = new Net_SSH2('srv-test');
if (!$ssh->login('user', $key)) {
    exit('Login Failed');
}
echo $ssh->exec('ls');
?>

and the output is

$ php test_key.php

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAqcmSbXneDVQsMe/kjKxkaaqKPTN5GUawoeknWL20exQN4HqCAklE
FMUcOd48ypAj4CZc9baGtjbpC3zCRDRcatJQTWbsP/P4vSe7728JPcVa0PVmqyi0
YF5rRAnkcNVA1X4EGriYhLYGTjeEZMjvrubBBgAsYUaRbyYBauSpp7GqAP3/sVk6
YeNRrs8nOLFYdp1bAmAlSemzixYWQ466jeHAfevD06WwSLwD1fh6Dfyt5kvsUZGp
7KldtHwBKg/YE947YSwIFkUVOQkyx7+7BgnDhTo8sgiY4in0YK9PIC5o/gBnBqw9
eBUjNFHTQSv8gRTEP68NfYipgy2VmcNPAQIDAQAB
-----END RSA PUBLIC KEY-----

Login Failed

the key file was generated with

ssh-keygen -f .ssh/id_rsa.pub -e -m pem

(the default format didn't work either) and I can normally login with the id_rsa.pub keyfile form the console. What am I missing ? Thank you


Solution

  • From your post:

    $key = new Crypt_RSA();
    $key->loadKey('key');
    echo file_get_contents('key');
    

    $key->loadKey('key'); isn't expecting a filename - it's expecting the actual key. So if you're having to do file_get_contents('key') to show the actual key then you'll have to do $key->loadKey(file_get_contents('key')).

    Also, you need to supply loadKey with the private key - not the public key. It looks like you're not because the key you did post has -----BEGIN RSA PUBLIC KEY----- in it. The private key is needed because that's how you verify your identity. You sign with the private key, the server verifies with the public key.