Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SFTP connection with key file using C# and .NET

I have a C# .NET project, where am trying to open an SFTP connection to a server and put a file to the server.

I have SFTP hostname, username and key file (.pem file).
I do not have a password here.

Please help me with something to use SFTP in C# and .Net.

like image 914
Sayan Sen Avatar asked Jan 17 '20 04:01

Sayan Sen


People also ask

How do I pass a private key using SFTP?

Right-click the icon and select “Add Key” and select your private key (PPK) file. Follow the prompt to enter your pass phrase and you're done. Now simply launch FileZilla Pro and connect to your server using SFTP using SSH2 with a username and an empty password. Don't forget to close pageant when you're done.

How does SFTP work with SSH keys?

So, for example, if you were using SSH-keys to gain access to an SFTP server, the public key would be shared with the server. That key is compared to the server's stored key for that username, which would have been stored on the server in advance. If the keys match, the user gains access.


1 Answers

Probably every SFTP/SSH library supports public key authentication.

For example:

  • SSH.NET (NuGet package):

    var privateKey = new PrivateKeyFile(@"C:\some\path\key.pem");
    var client = new SftpClient("example.com", "username", new[] { privateKey });
    client.Connect();
    

    If the private key is encrypted:

    var privateKey = new PrivateKeyFile(@"C:\some\path\key.pem", "passphrase");
    
  • WinSCP .NET assembly (NuGet package):

    SessionOptions sessionOptions = new SessionOptions
    {
        Protocol = Protocol.Sftp,
        HostName = "example.com",
        UserName = "username",
        SshHostKeyFingerprint = "ssh-rsa 2048 ...=",
        SshPrivateKeyPath = @"C:\some\path\key.ppk",
    };
    
    using (Session session = new Session())
    {
        session.Open(sessionOptions);
    
        // Your code
    }
    

    WinSCP needs the key converted to PPK format (You can use WinSCP GUI for that, or PuTTYgen). Also note that WinSCP verifies the SSH host key (SshHostKeyFingerprint). SSH.NET fails to do that by default, what is a security flaw.

    If the private key is encrypted, add PrivateKeyPassphrase or SecurePrivateKeyPassphrase.

    WinSCP GUI can generate a code template for you.

    (I'm the author of the library)

like image 127
Martin Prikryl Avatar answered Sep 24 '22 14:09

Martin Prikryl