Thursday, March 16, 2023

"Invalid private key file" exception while connecting SFTP server.

 I got a requirement to upload a file to SFTP. 

  • But while connecting SFTP they are using a private key file with a passphrase (password).
  • The same file I have used from the WinSCP application. It is connected and working.
  • But the same file I have triggered from C#. Then that time I got "Invalid private key file" exception error.
To resolve this we need to convert that private key from putty format to SSH Format.

Open WinSCP application. Under tools select "Run Puttygen".




Load the private key in WinSCP.
        



After loading the private key. In the conversions select the "Export OpenSSH key".





The newly generated key we can use in our code.
    var privateKey = new PrivateKeyFile(@"C:\some\path\key.pem", "passphrase");
    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");

Keep Daxing!!



No comments:

Post a Comment