在 C++ 中转换 std::string,使其可以是 C# 中的 byte[]

Convert a std::string in C++ so its can be a byte[] in C#

本文关键字:中的 byte 转换 C++ std string      更新时间:2023-10-16

所以,我正在尝试用C++加密消息并在C#中解密。我在 C# 中的解密需要以字节为单位的密钥和 IV,C++我使用 std::string 设置密钥和 IV,后来在加密中我使用它: (byte*)key.c_str()

如何获取此密钥

std::string szEncryptionKey = "Sixteen byte key";

如何将其硬编码为 C#

 byte[] key = ????

所以它使用正确的密钥和 IV 来解密?

命名空间System.Text中的Encoding类提供了一种方法来检索stringchar[]byte表示形式。

你可以像这样使用它:

Byte[] b = Encoding.UTF8.GetBytes("abc");

如果需要,还有其他编码,例如可用的UTF32

编辑:我已经检查了b的内容:对于编码UTF7UTF8ASCII和(我的当前(Default字符串"abc"的字节值是相同的:979899UTF32只加三个零;输出为 97 0 0 098 0 0 099 0 0 0

因为 std::string 是一个char数组的包装器,所以你可以使用它作为 .NET Marshal.Copy的输入,其函数类似于以下内容(在 C++/CLI 中(:

array<System::Byte>^ stoa(const std::string& str)
{
    array<System::Byte>^ result = gcnew array<System::Byte>(str.size());
    System::Runtime::InteropServices::Marshal::Copy(System::IntPtr((void*)str.c_str()), 
                                                    result, 0, result->Length);
    return result;
}

或者 C# 版本,假设你有其他方式str::string::c_str和字符串长度指针(P/Invoke?

byte[] Stoa(IntPtr strPtr, int strSize)
{
    var result = new byte[strSize];
    System.Runtime.InteropServices.Marshal.Copy(strPtr, result, 0, strSize);
    return result;
}

也许是这样的:

    static byte [] ToByteArray(string str)
    {
        byte[] a = new byte[str.Length];
        for (int i = 0; i < str.Length; i++)
        {
            a[i] = (byte)str[i];
        }
        return a; 
    }
    static void Main(string[] args)
    {
        byte[] key = ToByteArray("abc");
        int i = 0;
        foreach (byte b in key)
        {
            System.Console.WriteLine("key[{0}] : {1}", i++, b);
        }
    }

输出:

key[0] : 97
key[1] : 98
key[2] : 99