C#调用C++的AES加密库为什么显示不对呢

APPLYI 2017-01-08 10:44:15
C++ dll库代码如下

#include "AES.h"
#include<string.h>
#define AES_API __declspec(dllexport)
class AES {

AES_API unsigned char* Encrypt(unsigned char* str)
{
aes256_context ctx;
unsigned char key[32] = "123yr9012res012345678901";
unsigned char* buf = new unsigned char[256];
buf = str;
aes256_init(&ctx, key);
aes256_encrypt_ecb(&ctx, buf);
for (int i = 0; i < 256; i++)
printf("%c", buf[i]);
return buf;
}

AES_API unsigned char* Decrypt(unsigned char* str)
{
aes256_context ctx;
unsigned char key[32] = "123yr9012res012345678901";
unsigned char* buf = new unsigned char[256];
buf = str;
aes256_init(&ctx, key);
aes256_decrypt_ecb(&ctx, buf);
aes256_done(&ctx);
for (int i = 0; i < 256; i++)
printf("%c", buf[i]);
return buf;
}
}
;


C#调用

[DllImport("AES.dll",EntryPoint = "Encrypt")]
extern static IntPtr Encrypt(byte[] str);
static void Main(string[] args)
{
string str = "123456";
byte[] bx = new byte[256];
bx = Encoding.Default.GetBytes(str);
Encrypt(bx);
}


显示的结果与C++软件测试的不一样,而且数组传过去后再输出出来123456后面又多了一些字符,求告知为什么?新手不太懂
...全文
146 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
两种解决方法: 1. 将你的C#声明函数改为extern static IntPtr Encrypt(string str);直接传字符串就可以。 2. 将声明改为extern static IntPtr Encrypt(ref byte str); 然后调用的地方改为Encrypt(ref bx[0]); 表示将数组的首地址传入。 你试试,我建议使用第一种。
Forty2 2017-01-08
  • 打赏
  • 举报
回复
unsigned char*字符串是以一个零字符(\0)为结束标记。 而Encoding.Default.GetBytes(str)得到的字节数组,并包括零结束符。 C++寻找字符串零结束符的过程,就会缓存溢出,并把‘垃圾’内存算入,“123456后面又多了一些字符”的现象并不奇怪。 另,你的C++实现有内存泄漏(unsigned char* buf = new unsigned char[256])。

110,524

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧