"Renci.SshNet.Common.SshException: Invalid private key file" when loading SSH private key from configuration string using SSH.NET

Konduri Vikram picture Konduri Vikram · Mar 27, 2019 · Viewed 16.2k times · Source

I'm trying to send a file to some server using SFTP. During this process I'm getting the exception

Renci.SshNet.Common.SshException: Invalid private key file. at Renci.SshNet.PrivateKeyFile.Open(Stream privateKey, String passPhrase)

Generated the keys using PuTTYgen, shown below is an sample format of private key file. It has both the public and the private keys.

PuTTY-User-Key-File-2: ssh-rsa  
Encryption:none  
comment: rsa-key-20190327  
Public-Lines: 4  
AAAAB.....  
......  
Private-Lines: 8  
AAAAgQ......  
.......  
Private-MAC: 54901783....  

I copied the private key part from the above file in the config file and I'm accessing it as SftpKey in my code.

Got an OpenSSH format of the above key which looks like

------BEGIN RSA PRIVATE KEY-----  
MIIE....  
.......  
------END RSA PRIVATE KEY-------  

I copied only the key part from the above file and copied in my config file and ran my code. Issue was not resolved.

Below is the code i'm using for SFTP upload

var fileLength = data.Length;

var keyStr = ConfigurationManager.ConnectionStrings["SftpKey"].ConnectionString;
using (var keystrm = new MemoryStream(Convert.FromBase64String(keyStr)))
{
    var privateKey = new PrivateKeyFile(keystrm);
    using (var ftp = new SftpClient(_ftpServer, _ftpUser, new[] { privateKey }))
    {
        ftp.ErrorOccurred += ErrorOccurred;
        ftp.Connect();
        ftp.ChangeDirectory(_ftpPath);
        using (var dataStream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
        {
            ftp.UploadFile(dataStream, Path.GetFileName(message.MessageId), true,
                (length) => result = fileLength == (int)length);
        }
        ftp.Disconnect();
    }
}

Is there anything wrong with the code or what could be the issue? Any help is much appreciated.

Answer

Matt Kemp picture Matt Kemp · Aug 28, 2019

As this is the top answer for that error message, so I think it's worthwhile expanding on a point in your original question - converting to an OpenSSH format key.

Renci.SshNet can't use PuTTY keys that start with:

PuTTY-User-Key-File-2: ssh-rsa

You can use puttygen.exe to convert to the OpenSSH format

  1. load your key file in puttygen.exe
  2. Conversions > Export OpenSSH key (not the "force new file format" option)

This will make a key that starts with:

-----BEGIN RSA PRIVATE KEY-----

and that will work