当前位置: 动力学知识库 > 问答 > 编程问答 >

Encrypt in C++ and decrypt in C#

问题描述:

I have to encrypt a field in C++ application and decrypt it back in C#.

For encryption, i am using openssl library. The code is as follows -

 AES_KEY AESkey;

string plainText = "kumar atul" ;

unsigned char CBlock[1024]={0};

unsigned char Key[16];

char *MBlock = new char(plainText.size() ) ;

int pLen = plainText.size();

int plainTextLen=strlen((const char*) MBlock);

strcpy((char *) MBlock, plainText.c_str() );

for (int i=strlen((const char*) MBlock); i<16; i++)

{

MBlock[i] = 0;

}

unsigned char ckey[] = { 200, 5, 78, 232, 9, 6, 0, 4, 200, 5, 78, 232, 9, 6, 0, 4 };

AES_set_encrypt_key((const unsigned char *) ckey, 128, &AESkey);

unsigned char ivec[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 };

int num = 0 ;

AES_cfb128_encrypt( (const unsigned char *) MBlock, CBlock, 16, &AESkey, ivec, &num, AES_ENCRYPT) ;

std::string str(( char *) CBlock);

I wrote some programs in C# to encrypt the same string to same encrypted value, but they didn't work.

Please help.

Thanks in advance.

EDIT 1 :

I couldn't find the way to encrypt in base64 encoding in c++.

Also,

C# code to encrypt :

 private byte[] DESKey = { 200, 5, 78, 232, 9, 6, 0, 4, 200, 5, 78, 232, 9, 6, 0, 4 };

private byte[] DESInitializationVector = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 };

public string Encrypt(string value)

{

using (var cryptoProvider = new AesManaged())

using (var memoryStream = new MemoryStream())

using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(DESKey, DESInitializationVector), CryptoStreamMode.Write))

using (var writer = new StreamWriter(cryptoStream))

{

writer.Write(value);

writer.Flush();

cryptoStream.FlushFinalBlock();

writer.Flush();

return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);

}

}

分享给朋友:
您可能感兴趣的文章:
随机阅读: