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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…