Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

ssh - PHP ssh2_auth_pubkey_file(): Authentication failed using public key: Invalid key data, not base64 encoded

In PHP5.3.3 (on CentOS and apache2) I am attempting to connect to a SFTP via a php script. The code grabs the keys and server details from the constructor

function __construct(){
    $this->host     = 'servername.loc';
    $this->port     = SFTP_PORT;
    $this->auth_user    = 'username';
    $this->auth_pub     = '/data/home/username/.ssh/id_rsa.pub';
    $this->auth_priv    = '/data/home/username/.ssh/id_rsa';
    $this->auth_pass    = null;
    $this->connection   = null;
}

and uses those details to create the connection.

    private function connect(){
    if (!($this->connection = ssh2_connect($this->host, $this->port))) {
        $this->response  = array('code' => "20",
                                 "message" => "Error connecting to SFTP server.");
        return false;
    }
    if (!ssh2_auth_pubkey_file($this->connection, $this->auth_user, $this->auth_pub,
                                $this->auth_priv, $this->auth_pass)) {
        $this->response  = array('code' => "40",
                                 "message" => "Error authenticating to SFTP server with key.");
        $this->disconnect();
        return false;
    }
}

The result I get is an error on the call to ssh2_auth_pubkey_file().

The error is:

"ssh2_auth_pubkey_file(): Authentication failed for USERNAME using public key: Invalid key data, not base64 encoded"

There is no password on the key, and I can use these keys via CLI ssh to connect to the server manually.

I am stumped. Do I need to encode the keys somehow? Suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The prerequisite that you mention, namely the pubkey file not to have any comments and not even have a trailing newline is incorrect (and the newline thingy absurd when you think it through).

If your scriptfails, you have prob. sooner stumbled into the ssh2 bug that makes ssh2 fail when it is compiled wuth libgcrypt instead of openssl. The workaround is to create a PEM formatted copy of your private key file in PEM format with openssl:

~/.ssh> openssl rsa -in id_rsa -out id_rsa.pem

Then, in ssh2_auth_pubkey_file() in your PHP script, use id_rsa.pem as privkey file instead of id_rsa, and omit the passphrase. That should make it work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...