1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <string>
#include <stdlib.h>
#include <msclr\marshal_cppstd.h>
using namespace msclr::interop;
using namespace std;
using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Security::Cryptography;
_declspec(dllexport) string Encrypt(string strText, string strEncrKey)
{
// Initialize a Byte array with 8 bytes for Initial Vector of the Encryptor
array<Byte>^ IV= {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
//Handle exceptions
try
{
//Convert std:string to System:String for the GetBytes() Function
//Get the UTF8 Encoding for the System:String
String^ s = gcnew String(strEncrKey.c_str());
array<Byte>^ byKey = Encoding::UTF8->GetBytes(s);
//Convert std:string to System:String for the GetBytes() Function
//Get the UTF8 Encoding for the System:String
String^ s1 = gcnew String(strText.c_str());
array<Byte>^ InputByteArray = Encoding::UTF8->GetBytes(s1);
//Now create an instance of DESCryptoServiceProvider & MemoryStream and cross your fingers
DESCryptoServiceProvider^ des = gcnew DESCryptoServiceProvider;
MemoryStream^ ms = gcnew MemoryStream;
//Ok, here we go with the Cryptostream object! It took a little work, had to change the definition of IV
//from Byte IV[] = {x,x,x} to array<Byte>^ IV = {x,x,x}
CryptoStream^ cs = gcnew CryptoStream(ms, des->CreateEncryptor(byKey, IV), CryptoStreamMode::Write);
cs->Write(InputByteArray, 0, InputByteArray->Length);
cs->FlushFinalBlock();
//Convert the result from System::String to std::string and return it
String^ s2 = gcnew String(Convert::ToBase64String(ms->ToArray()));
string s3 = marshal_as<std::string>(s2);
return s3;
}
catch (exception& ex)
{
return ex.what();
}
}
|