在 C++ 中转换 std::string,使其可以是 C# 中的 byte[]
Convert a std::string in C++ so its can be a byte[] in C#
所以,我正在尝试用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
类提供了一种方法来检索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
。
因为 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
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- .cpp和.h文件中的模板专用化声明
- 反向给定链表中的K节点
- 正在查找文档以获得PS4平台的C++中的设备信息
- enum是C++中的宏变量还是整数变量
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 将字符串存储在c++中的稳定内存中
- 文本文件中的单词链表
- 递归函数计算序列中的平方和(并输出过程)
- 如何从C++中的依赖类型中获得它所依赖的类型
- C++中的"inline"关键字
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- Android:使用 c++ 中的 byte[] 参数调用 java 方法
- 三维数组中的C/C++DWORD到BYTE和BYTE到DWORD的转换
- 在 C++ 中转换 std::string,使其可以是 C# 中的 byte[]
- C++ 17 中的 std::byte 等同于 C# 中的字节
- 如何将 BYTE 数组中的两个字节存储为 int(或类似的东西)
- 模仿 java 结构中的C++并写入 byte[]
- SWIG将一个c++字符串包装成java中的byte[]