繁体   English   中英

如何使用 c#.net 中的 .key 文件连接到 SFTP 服务器

[英]How to Connect to SFTP server using .key file in c#.net

我有一个 C# .NET Windows 服务项目,我试图在其中打开到 SFTP 服务器的 SFTP 连接并将文件放入服务器。

我有 SFTP 主机名、用户名和密钥文件(.key 文件)。 我这里有密码。

请帮助我在 C# 和.Net 中使用 SFTP

我尝试按照下面提到的方式进行操作:-

using (SSHClient sshClient = new SSHClient(getKeyConnection(HostName, UserName, Port, Myprivatekey.key,PassPhrase)))
            {
                Console.WriteLine("Connecting to server.");
                sshClient.OperationTimeout = TimeSpan.FromSeconds(60);
                sshClient.Connect();
                Console.WriteLine("Is Connected to server " + sshClient.IsConnected);

            }

我的 GetkeyConnection 方法看起来像:

public static ConnectionInfo getKeyConnection(string host, string username, int port, string privateKeyFile,string password)
        {
            Console.WriteLine("Getting key Connection Info to establish Private Key SFTP");
            return new ConnectionInfo(host, port, username, privateKeyObject(username, privateKeyFile,password));
        }

我的 privateKeyObject 使用

private static AuthenticationMethod[] privateKeyObject(string username, string publicKeyPath,string password)
        {
            Console.WriteLine("Private key object method called.");
            PrivateKeyFile privateKeyFile = new PrivateKeyFile(publicKeyPath,password);      
            PrivateKeyAuthenticationMethod privateKeyAuthenticationMethod = new PrivateKeyAuthenticationMethod(username, privateKeyFile);
            return new AuthenticationMethod[] { privateKeyAuthenticationMethod };
        }

当我尝试连接时,我收到无效的私钥文件。 知道我们如何做到这一点。

我们有 X.509 证书,它是用中间 CA 签名的,并安装在我们的 SFTP 服务器上。 我们有一个私钥文件和一个密码,我在我的身份验证方法中发送了这些文件。 对于 SFTP,我们使用 Renci nuget package

Renci 要求私钥采用 openssl 格式。 该异常通常是无效密钥文件格式或丢失文件的结果。 您可以使用 putty gen、openssl 工具或 Java keytool 实用程序将密钥转换为正确的格式。

注意: 使用 SSH.NET 从配置字符串加载 SSH 私钥时出现“Renci.SshNet.Common.SshException: Invalid private key file”

当我们生成 X509 证书时,它会生成一个私钥,需要通过运行下面提到的命令将其转换为 RSA 私钥。

openssl rsa -in server.key -out server_new.key

确保以管理员模式打开 openssl。 这意味着您的密钥文件应以 --- Begin RSA Private Key---- 开头

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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