PHP7.3使用SSH密钥连接时出现消息认证算法兼容错误求助
解决PHP7.3下phpseclib SSH密钥连接报错:No compatible server to client message authentication algorithms found
问题根源
服务器升级为PCI合规配置后,限制了SSH连接允许的密钥交换、消息认证(MAC)算法集合,而phpseclib默认启用的算法集与服务器的合规配置不匹配,导致协商失败。终端能正常连接是因为OpenSSH默认支持的算法范围更广,覆盖了服务器的要求。
解决方案:显式指定服务器支持的算法
修改代码,在SSH2实例化后,显式设置服务器支持的密钥交换算法,并补充匹配的MAC算法,确保双方协商时能找到共同支持的算法:
$this->ssh = new SSH2(self::$config['host'], self::$config['port']); // 配置服务器支持的密钥交换算法 $this->ssh->setKexAlgorithms([ 'diffie-hellman-group1-sha1', 'diffie-hellman-group14-sha1', 'diffie-hellman-group14-sha256', 'diffie-hellman-group16-sha512', 'diffie-hellman-group18-sha512', 'diffie-hellman-group-exchange-sha1', 'diffie-hellman-group-exchange-sha256', 'ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521', 'curve25519-sha256', 'curve25519-sha256@libssh.org', 'sntrup4591761x25519-sha512@tinyssh.org' ]); // 配置PCI合规常见的MAC算法(匹配服务器要求) $this->ssh->setMACAlgorithms([ 'hmac-sha2-256', 'hmac-sha2-512', 'hmac-sha1' ]); $key = new RSA(); $key->setPassword(self::$config['password']); $key->loadKey(file_get_contents(self::$config['key'])); if (!$this->ssh->login(self::$config['username'], $key)) { exit('Login Failed'); }
调试排查(如果仍失败)
如果修改后还是无法登录,可开启phpseclib的日志功能,查看算法协商的详细过程,定位具体不兼容的算法项:
// 在实例化SSH2前开启日志 define('NET_SSH2_LOGGING', SSH2::LOG_COMPLEX); $this->ssh = new SSH2(self::$config['host'], self::$config['port']); // ... 其他配置代码 ... // 登录失败后输出日志 if (!$this->ssh->login(self::$config['username'], $key)) { echo $this->ssh->getLog(); exit('Login Failed'); }
内容的提问来源于stack exchange,提问作者Normal Dev
相关产品推荐
相关产品推荐

