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.
More info about SSH.NET here: https://github.com/sshnet/SSH.NET/
Using SSH.NET to connect 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 works :)
Bonus * the 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 :S
The key file (*.ppk) looks something similar to this
This is because the private key must be compatible with SshNet, so we have to convert the private key using PuTTY key Generator (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.
If you open the new file you will see that the key file now begins with
—–BEGIN RSA PRIVATE KEY—–
And ends with
—–END RSA PRIVATE KEY—–
Finally, this is a valid SSH private key and it works like a charm ;)
Hope you enjoy it!