将字符串转换为字节数组时出现异常

问题描述 投票:0回答:1

我正在使用 ssh.net 通过 SFTP 协议传输文件。我需要验证主机密钥指纹作为额外的安全层。为此,我编写了一个方法将字符串转换为字节数组进行比较,因为我将主机密钥保存为 xml 配置中的字符串,并且 SFTP 客户端将主机密钥作为字节数组保存。

using System;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Channels;
using FsLogger;
using Renci.SshNet;


namespace FsUtils.FileOperations
{
    public class FtpHandler
    {
        public string User { get; set; }

        public string Password { get; set; }

        public string Server { get; set; }


        public void UploadFileSftp(string sourceFile, string targetDir, string sshHostKeyFingerprint)
        {
            using (var client = new SftpClient(Server, User, Password))
            {
                client.HostKeyReceived += (sender, e) =>
                {
                    byte[] receivedFingerprint = e.FingerPrint;
                    byte[] providedFingerprint = StringToByteArray(sshHostKeyFingerprint);

                    e.CanTrust = receivedFingerprint.SequenceEqual(providedFingerprint);
                };
                try
                {
                    client.Connect();

                    if (client.IsConnected)
                    {
                        using (var fileStream = File.OpenRead(sourceFile))
                        {
                            client.UploadFile(fileStream, targetDir);
                        }
                    }
                    Logging.Info("File uploaded successfully");
                }
                catch (Exception ex)
                {
                    Logging.Error($"Exception occurred - {ex.Message}");
                }
                finally
                {
                    if (client.IsConnected)
                        client.Disconnect();
                }
            }
        }

        private byte[] StringToByteArray(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                .Where(x => x % 2 == 0)
                .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                .ToArray();
        }
    }
}

现在的问题是在将我的字符串主机密钥转换为字节数组时,它会抛出异常。

<![LOG[Failed: Exception occurred - Additional non-parsable characters are at the end of the string.]LOG]!>

我从 knwon-hosts 文件中收集了主机密钥,并复制了该密钥及其加密算法。看起来像这样-

ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBP4cDyvxP/kbZ1XrPxxyMshbTtrY605xu5VL37uZt9mv7d2ZqD3TSWoEcUgHgtzGuRzkGTfDXdT9J=

如何验证主机密钥指纹而不出现任何问题?我非常感谢您的善意帮助。

c# sftp ssh.net
1个回答
0
投票

我可能会选择这样的方式,而不是使用 LINQ 查询:

private byte[] StringToByteArray(string hex)
{
    var numericValueOfHex = uint.Parse(hex, System.Globalization.NumberStyles.AllowHexSpecifier);

    return BitConverter.GetBytes(numericValueOfHex);
}

您可以在 Microsoft 的这篇文章“如何在十六进制字符串和数字类型之间进行转换”中阅读更多相关信息。

© www.soinside.com 2019 - 2024. All rights reserved.