phpseclib使用SHA256连接SFTP失败求助:key_verify格式错误
Let's break down why switching to SHA256 is causing your key_verify: invalid format error and walk through actionable fixes to resolve it:
1. Adjust the Order of RSA Configuration
A common pitfall with phpseclib is that loading the private key can reset previously set hash configurations. Try moving your hash settings after loading the key to avoid overwrites:
$Key = new RSA(); $Key->setPassword("password"); // Load the private key first $Key->loadKey(file_get_contents('path_to_RSA_private_key')); // Now apply SHA256 settings $Key->setHash('sha256'); $Key->setMGFHash('sha256'); $sftp = new SFTP($IP_addr, $port_number); if (!$sftp->login('username', $Key)) { echo date('Y/m/d H:i:s')." SFTP login failed to $IP_addr"; }
2. Explicitly Define the Signature Mode
phpseclib may require a clear signature format to work with SHA256. Add this line right after setting your hash algorithms:
$Key->setSignatureMode(RSA::SIGNATURE_PKCS1);
This enforces the widely compatible PKCS#1 v1.5 signature standard, which most SFTP servers expect for RSA-based authentication.
3. Verify Server-Side Algorithm Support
Even with default settings, some SSH servers might not enable RSA-SHA2 algorithms out of the box. Check your server's sshd_config for the PubkeyAcceptedAlgorithms directive—ensure it includes at least one of these:
rsa-sha2-256@openssh.com(the modern SHA256-specific RSA signature)ssh-rsa(if your server supports SHA256 signatures for the legacy ssh-rsa algorithm)
If the directive is missing, adding it with the above values can fix compatibility mismatches.
4. Enable phpseclib Debug Logging
To get granular visibility into the SSH handshake and key verification process, enable debug logging:
define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX); $Key = new RSA(); // ... rest of your configuration code ... if (!$sftp->login('username', $Key)) { echo date('Y/m/d H:i:s')." SFTP login failed to $IP_addr"; // Print debug log to diagnose negotiation/verification issues echo "<pre>".$sftp->getLog()."</pre>"; }
The log will show which algorithms are being negotiated, how your key is being signed, and exactly where the verification fails—this is critical for pinpointing server-side or client-side mismatches.
Start with the first two fixes, as they're the most likely to resolve your issue without server changes. If those don't work, the debug log will give you the details needed to tweak server settings further.
内容的提问来源于stack exchange,提问作者Schonke

