Upload file to SFTP using pem file in c#
BY Abhishek Singh Feb 10, 2022.

PEM (Privacy Enhanced Mail) is a base64 container format for encoding keys and certificates.  
PPK(Putty Private Key) is a windows ssh client, it does not support .pem format. Hence you have to convert it to .ppk format using PuTTyGen. 
A lot of open source software, as well as AWS, generate .pem files for you to use. But if you are using something like PuTTY or WinSCP, you will most likely need to use a .ppk file. Converting .pem files to .ppk is easy using a program called PuTTYgen. 
Files created by PuTTYgen are known as PPK files. PPK files are PuTTY Private Key Files developed by Putty and they serve as storage for the private keys the program generated. These files are used to enable communication securely with another party having the corresponding public key. 


static voidSFTP_Service(string host, string userid, string pemfilename, string ftpPath, string InputDirPath, string FileName)

{

static List<string> Log_List= new List<string>();

string PEM_Path=System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);

                    SFTP_Config config = new SFTP_Config();

                    config.Host = host;

                    config.UserName = userid;

                    config.PEM_File = PEM_Path+ pemfilename; // @"D:\sftp.pem ---key filepath ";

                    SFTP_ServiceSFTPService_obj = newSFTP_Service(config);

                    bool uploadstatus = SFTPService_obj.UploadFileUsingPEM(InputDirPath +FileName, ftpPath + FileName, ref Log_List);

}

 

 

 

 

class SFTP_Service

    {

        private readonly SFTP_Config _config;

        public SFTP_Service(SFTP_Config sftpConfig)

        {

            _config = sftpConfig;

        }

        public boolUploadFileUsingPEM(stringlocalFilePath, stringremoteFilePath, ref List<string> Log_List)

        {

            bool uploadstatus = false;

            var privateKey = new PrivateKeyFile(_config.PEM_File);

           

            try

            {

              

                try

                {

                    using (var sftp = newSftpClient(_config.Host, _config.UserName, new[] { privateKey }))

                    {

                        sftp.Connect();

                        using (var file = File.OpenRead(localFilePath))

                        {

                            sftp.BufferSize = 4* 1024;

                           sftp.UploadFile(file, remoteFilePath);

                            Log_List.Add("Finished uploading file " + localFilePath + " to " + remoteFilePath + " " + System.DateTime.Now);

                        }

                        sftp.Disconnect();

                        uploadstatus = true;

                    }

                }

                catch (Renci.SshNet.Common.SshConnectionException)

                {

                    Log_List.Add("Cannot connect to the server. " + localFilePath + " to " + remoteFilePath + " " + System.DateTime.Now);

                    uploadstatus = false;

                }

                catch (System.Net.Sockets.SocketException)

                {

                    Log_List.Add("Unable to establish the socket. " + localFilePath + " to " + remoteFilePath + " " + System.DateTime.Now);

                    uploadstatus = false;

                }

                catch (Renci.SshNet.Common.SshAuthenticationException)

                {

                    Log_List.Add("Authentication of SSH session failed. " + localFilePath + " to " + remoteFilePath + " " + System.DateTime.Now);

                    uploadstatus = false;

                }

                catch (Exception ex)

                {

                    Log_List.Add("Failed in uploading file " + localFilePath + " to " + remoteFilePath + " " + System.DateTime.Now + "~>" + ex.Message);

                    uploadstatus = false;

                }

            }

            catch (Exception ex)

            {

                uploadstatus = false;

                Log_List.Add("Error " +localFilePath + " to " + remoteFilePath + " " + System.DateTime.Now + "~>" + ex.Message);

            }

            return uploadstatus;

        }

    }

 

 

Renci.SshNet.Common.SshException: 'openssh key type: ssh-rsa is not supported'




Renci.SshNet.Common.SshException: 'Invalid private key file.'





Youcan use ssh-keygen toconvert the key to the classic OpenSSH format:

ssh-keygen -p -f file -m pem -P passphrase -N passphrase(if the key is not encryptedwith a passphrase, use "" insteadof passphrase)For Windows users: Notethat ssh-keygen.exe is now built-in inWindows 10. And can be downloaded from MicrosoftWin32-OpenSSH project for older versions ofWindows.


On Windows, you can also usePuTTYgen (from PuTTY package):·        Start PuTTYgen·        Load the key·        Go to Conversions > Export OpenSSHkey.
For RSA keys, it will use the classic format.


If you are creating a new keywith ssh-keygen, just add -m PEM togenerate the new key in the classic format:

ssh-keygen -m PEM















Leave your comment

Popular Posts