I have a C# .NET Windows service project, where am trying to open an SFTP connection to a SFTP server and put a file to the server.
I have SFTP hostname, username and key file (.key file). I do have a passphrase here.
Please help me with something to use SFTP in C# and .Net
I tried to do it in the below mentioned way :-
using (SSHClient sshClient = new SSHClient(getKeyConnection(HostName, UserName, Port, Myprivatekey.key,PassPhrase)))
{
Console.WriteLine("Connecting to server.");
sshClient.OperationTimeout = TimeSpan.FromSeconds(60);
sshClient.Connect();
Console.WriteLine("Is Connected to server " + sshClient.IsConnected);
}
Where my GetkeyConnection menthod is looks like :
public static ConnectionInfo getKeyConnection(string host, string username, int port, string privateKeyFile,string password)
{
Console.WriteLine("Getting key Connection Info to establish Private Key SFTP");
return new ConnectionInfo(host, port, username, privateKeyObject(username, privateKeyFile,password));
}
My privateKeyObject uses
private static AuthenticationMethod[] privateKeyObject(string username, string publicKeyPath,string password)
{
Console.WriteLine("Private key object method called.");
PrivateKeyFile privateKeyFile = new PrivateKeyFile(publicKeyPath,password);
PrivateKeyAuthenticationMethod privateKeyAuthenticationMethod = new PrivateKeyAuthenticationMethod(username, privateKeyFile);
return new AuthenticationMethod[] { privateKeyAuthenticationMethod };
}
When I am trying to connect i am getting invalid private key file. Any idea how we can do this.
We have X.509 certificates which is signed with intermediate CA and is installed on our SFTP server. and we have a private key file and a passphrase which i am sending in my Authentication method. For SFTP we are using Renci nuget package
When we generate a X509 Certificate it generate a Private key which needs to be converted into RSA private key by running a below mentioned command.
openssl rsa -in server.key -out server_new.key
Make sure you open openssl in Administrator mode. Which means your key file should start with --- Begin RSA Private Key----