如何将十六进制字符串转换为普通文本字符串 C#

本文关键字:字符串 文本 转换 十六进制 | 更新日期: 2024-11-06 17:07:55

我们有一个keyMaterial HEX字符串。看起来像这样

453F1287225ED9971D389A35F8D1032E7748DD0B88302F7C6C194626D4C8659B000000000E80000000020000000200000047C2CA7B9A1F1C343CA228CC314A42F063A240E17624F886AF6CE9A135CAF653100

00000D30489E536548F129E43240A26344811400000009EE2F5549B1447548ADADDD60A212C22DC2F9B2DC67D8E567B48B3847A525244A2F575AAFFB3AECD0385612BE7C38CA403BE6B5DFA8BEDEFBFA35C5ECC1818AB

您可以看到整个文件。我们如何用 C# 将此十六进制代码转换为普通文本字符串?我有一些关于C++的例子,它对我没有帮助。你能给出一个建议吗?

此字符串的编码16291388(但这不是问题的解决方案)

如何将十六进制字符串转换为普通文本字符串 C#

如果您从这里获取转换方法,并使用正确的编码转换生成的字节数组来扩展该方法,那么您就在那里。

public static byte[] StringToByteArray(String hex)
{
    int NumberChars = hex.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes;
}
// use UTF8 in this sample:
string output = Encoding.UTF8.GetString(StringToByteArray(hex));

如果你看一下OP的原始文件,他正在尝试解码无线配置文件的密钥材料。

这些数据不仅以十六进制编码,而且还被加密,这就是为什么仅将其转换为字符串会导致无意义的数据。

<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
    <name>TP-LINK_D84690</name>
    <SSIDConfig>
        <SSID>
            <hex>54502D4C494E4B5F443834363930</hex>
            <name>TP-LINK_D84690</name>
        </SSID>
    </SSIDConfig>
    <connectionType>ESS</connectionType>
    <connectionMode>auto</connectionMode>
    <MSM>
        <security>
            <authEncryption>
                <authentication>WPA2PSK</authentication>
                <encryption>AES</encryption>
                <useOneX>false</useOneX>
            </authEncryption>
            <sharedKey>
                <keyType>passPhrase</keyType>
                <protected>true</protected>
                <keyMaterial>01000000D08C9DDF0115D1118C7A00C04FC297EB01000000E72F4D29E2AD8E40BBAD5B02842DA10000000000020000000000106600000001000020000000453F1287225ED9971D389A35F8D1032E7748DD0B88302F7C6C194626D4C8659B000000000E800000000200002000000047C2CA7B9A1F1C343CA228CC314A42F063A240E17624F886AF6CE9A135CAF65310000000D30489E536548F129E43240A26344811400000009EE2F5549B1447548ADADDD60A212C22DC2F9B2DC67D8E567B48B3847A525244A2F575AAFFB3AECD0385612BE7C38CA403BE6B5DFA8BEDEFBFA35C5ECC1818AB</keyMaterial>
            </sharedKey>
        </security>
    </MSM>
</WLANProfile>

此数据已加密,因此您不能仅将其解码为字符串。

    byte[] bytes = StringToByteArray(your hex string here);
    var strArray = (Encoding.Default.GetString(
             bytes,
             0,
             bytes.Length - 1)).Split(new string[] { "'r'n", "'r", "'n", "'0" },
                                         StringSplitOptions.None);
    string output = string.Join("", strArray);

StringToByteArray 代码在这里

    public static 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();
    }