Jun 10, 2021

Connect via SFTP using SSH.NET

Disclaimer: This is not a financial-related post. :)

Collecting data from banking providers

In these times of APIs-everywhere, it may sound like an anachronism the use SFTP to connect to a remote server and get a list of files for exchanging information, but in the financial world (sadly) it’s more common than you think.

In my current project I’ve to connect to a remote server via Secure File Transfer Protocol (aka SFTP) using a user name, a RSA private key and a phassphrase. Once connected, the goal is to read some files from a remote folder and download them to a local folder.

To accomplish this I recommend you to use SSH.NET, one of the most popular SSH libraries for .NET, available on nuget.

SSH.NET on NuGet

More info about SSH.NET here.

Connecting to the server

The most difficult part here is configure the connection, as usual. We need to provide the server url and port, in combination with the username and a file that contains the private key of the RSA certificate, and -of course- the passphrase.

Here’s the final code, and it just works :)

Take a look at the highlighted line (7). The key here is creating a file that contains the privateKey. I recommend you to use filezilla or similar to test the connection and save it to a file. Your file should looks something like this:

PuTTY-User-Key-File-2: ssh-rsa
Encryption: aes256-cbc
Comment: rsa-key-KBL-20171006
Public-Lines: 6
Private-Lines: 14
Private-MAC: d288fffe72914eb62ed60a7e50fd8ce775

Bonus (trick)

I’ve spent a lot of time before it works receiving a SSH exception “Invalid private key file”, but the same key file works fine when using the app Filezilla to connect, so #WhatTheHell is going on 😬

Finally I realized this is because the private key must be compatible with SshNet, so we have to convert the private key using PuTTY key Generator (in my case, the same app we used to create the certificate). Once opened in PuTTY, just export your file key to OpenSSH and use this new ppk file instead of the previous one.

Export OpenSSH key

If you open the new file you will see that the key file now begins with:


And ends with:


Now this is a valid SSH private key and it shoud work like a charm ;)

Happy codding!

about the author

Albert González

read more
your independent wealth managers

Get unparalleled peace of mind of your wealth

GET in touch
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Fimarge Societat Financera d’Inversió SA
C/ Bonaventura Armengol, 10
Ed. Montclar Bloc 1, 5è 1a
Andorra la Vella
Nº Registre Societat: 5711
Nº Registre Tributari: A-700866-T
Nº Autorització AFA: SFI-04/95 (20/04/1988)