【问题标题】:Convert a std::string in C++ so its can be a byte[] in C#在 C++ 中转换 std::string 以便它可以是 C# 中的 byte[]
【发布时间】:2018-03-08 20:09:50
【问题描述】:

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

我怎样才能得到这个密钥

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

如何将其硬编码到 C# 中

 byte[] key = ????

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

【问题讨论】:

  • 尽管有任何便利方法和chars 和字节之间的任何“概念隐式转换”,加密将字节作为数据和密钥并产生字节。没有文本,只有编码文本,因此如果您使用文本来创建此类字节,则必须使用特定的字符编码并在各处共享该知识。对于字符串文字,编码是编译器用于项目的“目标字符集”。

标签: c# c++


【解决方案1】:

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

你可以这样使用它:

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

如果需要,还可以使用其他编码,例如 UTF32。

编辑:我检查了b 的内容:对于编码UTF7、UTF8、ASCII 和(我的当前)Default,字符串“abc”的字节值是相同的:97、98 和 99。 UTF32 只加了三个零;输出为97 0 0 0、98 0 0 0 和99 0 0 0。

【讨论】:

  • 但是有了这个,我需要知道在 c++ 中完成的完全相同的编码?但我不确定是哪一个?
  • @KunoHeltborg 在 Visual C++ 中很可能是 UTF8
  • @KunoHeltborg 我已经用不同编码的一些结果更新了答案。
  • 好的,有没有我可以检查一下这个; (byte*)key.c_str().. 给我的字节流和这个 Encoding.UTF8.GetBytes("abc");..
  • 只是为了查看这个 (byte*)key.c_str() 的输出。来自 C# 的部分很简单,可以看到 :)
【解决方案2】:

因为 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;
}

【讨论】:

    【解决方案3】:

    可能是这样的:

        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
    

    【讨论】:

    • 有一个更干净的方法:Byte[] b = Encoding.UTF8.GetBytes("abc");
    • @SebastianHofmann 将此作为答案,我将删除我的答案。
    • 完成,但无需删除您的答案。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2012-12-11
    • 2012-01-02
    • 1970-01-01
    • 2022-06-29
    相关资源
    最近更新 更多