如何将HEX字符串转换为普通文本字符串C#

时间:2016-04-21 08:01:03

标签: c# encryption hex

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

  

453F1287225ED9971D389A35F8D1032E7748DD0B88302F7C6C194626D4C8659B000000000E800000000200002000000047C2CA7B9A1F1C343CA228CC314A42F063A240E17624F886AF6CE9A135CAF65310000000D30489E536548F129E43240A26344811400000009EE2F5549B1447548ADADDD60A212C22DC2F9B2DC67D8E567B48B3847A525244A2F575AAFFB3AECD0385612BE7C38CA403BE6B5DFA8BEDEFBFA35C5ECC1818AB

您可以看到whole file。我们如何使用C#将此HEX代码转换为普通文本字符串?我有一些关于C ++的例子,它对我没有帮助。你能提出建议吗?

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

3 个答案:

答案 0 :(得分:3)

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

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));

答案 1 :(得分:2)

如果您查看OP的原始文件,他正在尝试解码无线配置文件的keyMaterial。

这个数据不只是以十六进制编码,它也是加密的,这就是为什么只是将它转换为字符串会导致无意义的数据。

<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>

此数据已加密,因此您无法将其解码为字符串。

答案 2 :(得分:0)

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