Chilkat Crypt.NET Components Home

Managed C++ to AES Encrypt CLI Byte Array

Back

Demonstrates how to use the Chilkat Crypt2 class to encrypt a managed byte array in Managed C++ (Visual Studio 8.0)
// Managed C++ to save a byte array to a binary file.
void SaveByteArray(array<unsigned char,1>^ bytArray, String^ fname)
	{
		FileStream^ fStream = gcnew FileStream(fname, FileMode::Create);
		
		BinaryWriter^ bw = gcnew BinaryWriter(fStream);

		bw->Write(bytArray);

		bw->Close();
		
		fStream->Close();
	}

void TestCrypt(void)
{
	Chilkat::Crypt2 crypt;
	crypt.UnlockComponent("30-day trial");

	crypt.CryptAlgorithm = "aes";
	crypt.KeyLength = 256;

	// The new array syntax in Managed C++ (for a CLI array) is
	// to declare a handle to it and then gcnew it.  The template parameter
	// is the element type of the array.
	
	// This declares an array of 32 bytes (32 * 8 bits/byte = 256 bits, which 
	// is our key length).
	array<unsigned char,1>^ sKey = gcnew array<unsigned char,1>(32);

	int i;
	for (i=0; i<32; i++) sKey[i] = i;

	crypt.SecretKey = sKey;

	// Create some data to encrypt.
	array<unsigned char,1>^ myData = gcnew array<unsigned char,1>(100);
	for (i=0; i<100; i++) myData[i] = i;

	array<unsigned char,1> ^encryptedData = crypt.EncryptBytes(myData);

	SaveByteArray(encryptedData,"encrypted.dat");

	// Now decrypt it...
	array<unsigned char,1> ^decryptedData = crypt.DecryptBytes(encryptedData);
	SaveByteArray(decryptedData,"decrypted.dat");

}