經過RTFM和做了一些測試後,我發現libssh2_userauth_publickey_fromfile
將返回一個不同的錯誤代碼,具體取決於密鑰未被服務器接受還是密碼錯誤。
因此,這是一個相當低效的解決方案(因爲它調用libssh2_userauth_publickey_fromfile
,因此協議的所有密鑰交換部分至少需要兩次)。
int nAttempts = 3; // number of attempts the user gets at entering the passphrase
// Try authenticating with an empty passphrase
int err = libssh2_userauth_publickey_fromfile(session, user, pub, priv,"");
if (err == 0)
{
fprintf(stderr, "You shouldn't use keys with an empty passphrase!\n");
}
else if (err == LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED)
{
// if we get here it means the public key was initially accepted
// but the private key has a non-empty passphrase
char p[BUFSIZ];
for (int i = 0; i < nAttempts; ++i)
{
get_passphrase(p); // assume this gets the passphrase
err = libssh2_userauth_publickey_fromfile(session, user, pub, priv,p);
if (err != LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED) break;
}
}
if (err != 0)
{
fprintf(stderr, "Authentication using key %s failed!\n", priv);
}
爲了完整起見,函數使用溶液來this question提示輸入密碼短語用戶。