-1

Firstly I generated the keys using

var keygen = new SshKeyGenerator.SshKeyGenerator(2048);

var privateKey = keygen.ToPrivateKey();
var publicSshKey = keygen.ToRfcPublicKey();

The private key generated the following string:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBA... etc.
-----END RSA PRIVATE KEY-----

I'm now trying to create a new Renci.SshNet.PrivateKeyFile object to be used to create the SftpClient object. I tried loading the RSA private Key string in a number of ways similar to:

using (var keyStream = new MemoryStream(Encoding.ASCII.GetBytes(ReturnKey())))
{
    var privateKy = new PrivateKeyFile(keyStream);

}

The method ReturnKey() simply returns a string of the private key -----BEGIN RSA PRIVATE KEY----- etc. I've tried with and without the "-----BEGIN RSA and -----End RSA" and I get the same result:

Error {Invalid private key file.}

I have all the details to connect to sFTP server i.e. User, DNS, Port, Path. which has the public key generated, I just can't load the private key as a start.

This is the first time I've had to connect to sFTP using SSH. Any help would be much appreciated, thank you.

James
  • 19
  • 2
  • Please [edit] your question to show all of the relevant code from your program, in particular the code which is producing the error. Ideally, you should post a complete, simple program which demonstrates the problem. – Kenster Aug 16 '21 at 12:30
  • `new PrivateKeyFile(new MemoryStream(Encoding.ASCII.GetBytes(new SshKeyGenerator.SshKeyGenerator(2048).ToPrivateKey())))` does not throw any exception for me (I've used NuGet packages SshKeyGenerator 1.1.40 and SSH.NET 2020.0.1). – Martin Prikryl Aug 20 '21 at 19:12
  • @MartinPrikryl this also worked for me, so it must be the way I'm storing the privatekey and resuing it, I'll try a few things initially. – James Aug 21 '21 at 16:18
  • @Kenster fair point, I'll add all the relevant code. – James Aug 21 '21 at 16:19

1 Answers1

-1

Looks like it was the way I was adding the private key text; instead I saved the key to a txt file and loaded directly. I think there were additional characters, tabs/returns perhaps in the string from ReturnKey() function, so it would have helped if I added the full code.

James
  • 19
  • 2