简体   繁体   中英

"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:

  • With the given.ppk file, I converted it to OpenSSH format with PuTTYgen
  • From the resulting private key, I copied it into my code and tried to create an SftpClient with it.

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

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-----";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM