0

I'm very new to C#, but not to programming. I'm trying to use SSH.NET to make an SSH connection using a private key, using the example is here:

public ConnectionInfo CreateConnectionInfo()
{
    const string privateKeyFilePath = @"C:\some\private\key.pem";    
    ConnectionInfo connectionInfo;
    using (var stream = new FileStream(privateKeyFilePath, FileMode.Open, FileAccess.Read))
    {
        var privateKeyFile = new PrivateKeyFile(stream);
        AuthenticationMethod authenticationMethod =
            new PrivateKeyAuthenticationMethod("ubuntu", privateKeyFile);

        connectionInfo = new ConnectionInfo(
            "my.server.com",
            "ubuntu",
            authenticationMethod);
    }

    return connectionInfo;
}

I don't have the key stored in a file, it comes from another source and I have it in a string. I realize I could write it to a temporary file, then pass that filename, then trash the file, but I'd prefer not to have to write it out to disk if possible. I don't see anything in the documentation that lets me pass a string for this, only a filename. I've tried something like this to convert the string to a stream:

byte[] private_key     = Encoding.UTF8.GetBytes(GetConfig("SSHPrivateKey"));
var private_key_stream = new PrivateKeyFile(new MemoryStream(private_key));

And then pass private_key_stream as the second parameter of PrivateKeyAuthenticationMethod. There seem to be no complaints from the compiler, but the method doesn't appear to actually be getting the key (SSH doesn't authenticate, and external attempts like PuTTY using this key to the server do work), so it looks like I'm missing something.

Any thoughts on how to accomplish this without writing out a temp file?

Nick Coons
  • 3,682
  • 1
  • 19
  • 21
  • 3
    You can create a stream from a string by using StringReader(string) method. – jdweng Sep 03 '16 at 21:29
  • I did some Googling on `StringReader`, and it appears to be a class rather than a method, so I'm not sure if I'm looking at the right thing. I tried `var private_key = new PrivateKeyFile(new StringReader(GetConfig("SSHPrivateKey")));`, but I get an error "cannot convert from 'System.IO.StringReader' to 'System.IO.Stream". So it looks like this returns type `StringReader` rather than `Stream`. I'm sure I'm missing something that would be obvious to seasoned C# coders, so just looking for some direction on this.. thanks! – Nick Coons Sep 04 '16 at 06:15
  • I ended up putting together a custom extension to `String` so that I could do `"my_key".ToStream()`, and that's working well. The code for that was provided in Josh G's answer here: http://stackoverflow.com/questions/1879395/how-to-generate-a-stream-from-a-string – Nick Coons Sep 04 '16 at 06:55

0 Answers0