Connecting to SFTP with key file using SSH.NET (Permission denied (publickey))

Ralph picture Ralph · Apr 16, 2017 · Viewed 13.1k times · Source

I have a C# console application in Visual Studio 2008 and .NET Framework 3.5.

For testing purposes, I have installed an FTP Server in my local machine and configure it. I have downloaded and installed this free small FTP Server: freeFTPd. It is really easy, it takes me about 10 minutes.

Once I have configured it, I have successfully connected using PasswordA uthentication Method using my C# console app.

Now I am trying to only connect to my local FTP server using key based file only.

So the code I have implemented is the following:

var keyFile = new PrivateKeyFile(@"C:\Program Files (x86)\freeFTPd\freeftpd.key");
var keyFiles = new[] { keyFile };


var methods = new List<AuthenticationMethod>();
methods.Add(new PrivateKeyAuthenticationMethod(username, keyFiles));

var con = new ConnectionInfo(host, port, username, methods.ToArray());
using (SftpClient client = new SftpClient(con))
{
    client.Connect();
    // Do some stuff below
}

As you can see in the above code, I am using freeftpd.key as private key file. This file has been created once freeFTPd is installed. During installation, freeFTPd asked me to create a new private key file so I answered 'yes'. Now I am using it but the problem is that I can connect to my FTP local server using this private key file. I have opened this file, and it starts with following line:

-----BEGIN RSA PRIVATE KEY-----

and ends with:

-----END RSA PRIVATE KEY-----

Below them there is a bunch of encrypted data.

I have read somewhere that this file must begin with this line.

Anyway I cannot connect to my FTP server.

From freeFTPd control panel, in the section for SFTP, I can create RSA and DSA keys (512, 1024 or 2048 bits of lenght). These files are generated as RSAKey.cfg and DSAKey.cfg and their content are similar to private key file 'freeftpd.key' generated during freeFTPd installation process. If I use RSAKey.cfg or any other just created from freeFTPd it is not working. The error message that appears is:

Permission denied (publickey).

So What I am doing wrong? I have no idea about certificates, private key files... Any help will be highly appreciated.

Answer

Karl picture Karl · Oct 15, 2018

In my case I got the message ( (Permission denied (publickey))) when PasswordAuthentication was missing. The server needed the certificate an username/password.

Please try to add both methods as described below.

I used a combination of SSH.NET as a client and syncplify.me Server.

var keyFile = new PrivateKeyFile(config.SFTPPrivateKeyFilename);
var keyFiles = new[] { keyFile };
var methods = new List<AuthenticationMethod>
{
    new PasswordAuthenticationMethod(config.SFTPUser, config.SFTPPassword),
    new PrivateKeyAuthenticationMethod(config.SFTPUser, keyFiles)
};

return new ConnectionInfo(config.SFTPServer, 22, config.SFTPUser, methods.ToArray());