MERNboy
MERNboy

Reputation: 165

"Invalid private key file" when authenticating to SFTP with SSH.NET using a key in a string

I have a program where I want to connect to an SFTP host and push/pull files. The host requires a private key to connect. Using these posts for guidance:

I did the following:

The following is the code I have:

SftpClient sftp = null;

if (bHost.Equals("sftp.sftpHost.com"))
{
    var keyStr = @"-----BEGIN RSA PRIVATE KEY-----
    Proc-Type: 4,ENCRYPTED
    DEK-Info: DES-EDE3-CBC,15BEAB6C0B73F39A

    ***private key***
    -----END RSA PRIVATE KEY-----";

    using (var keystrm = new MemoryStream(Encoding.UTF8.GetBytes(keyStr)))
    {
        var privateKey = new PrivateKeyFile(keystrm, "passPhrase");
        sftp = new SftpClient(bHost, bUser, new[] { privateKey });
    }
} else
{
    sftp = new SftpClient(bHost, bPort, bUser, bPw);
}

return sftp;
                   

Is there something wrong with my code, or possibly the way I generated the OpenSSH formatted key was incorrect?

I noticed in other example key strings, they do not include the following:

Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,15BEAB6C0B73F39A

Upvotes: 0

Views: 5159

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202088

It's probably the leading spaces in your multi-line string. They cannot be there.

Remove them.

    var keyStr = @"-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,15BEAB6C0B73F39A

***private key***
-----END RSA PRIVATE KEY-----";

Upvotes: 1

Related Questions